Shop OBEX P1 Docs P2 Docs Learn Events
For() counter: getting float values — Parallax Forums

For() counter: getting float values

I need a loop where I can use these values in a calculation: 0.00, 0.01, 0.02, 0.03... 3.00.
I tried a float counter: fail.
I tried an integer counter for 0-300 then divided by 100: fail because int/int = int
It works as below with int counter then (float)int/100.
Is there an obviously better way to get that series of values?
- Thanks

int main()
{
int myInteger;
float myFloat;
for(myInteger=0;myInteger<=300;myInteger++)
{
myFloat = (float)myInteger/100;
print("\n%d %f",myInteger,myFloat);
}
}

Comments

  • The way you're doing it is pretty much the only way. You could write myInteger / 100.0 but that would translate into essentially what you have. The compiler converts myInteger to a float implicitly or explicitly then coerces 100 to float if not already done
  • altosackaltosack Posts: 132
    edited 2015-09-11 02:39
    Another way that is computationally less expensive for processors without hardware floating point like the prop is to use an integer counter like you're doing, but initialize myFloat to 0.0 and then have myFloat += 0.01 in the loop so you're adding each time instead of dividing.

    You'll accumulate a slight error after 300 adds, but only you can determine if it's an acceptable tradeoff for your application.

    Once you do this, another slight optimization would be to count down the integer counter (i=300; i>=0; i--) since it compiles to DJNZ, but it makes the code intent slightly less obvious to casual readers (comments are your friend !).
  • Thanks. Both answers taught me something about how floats are handled. And I've learned that there isn't an obviously better technique.
  • I like altosack's solution the most. Keep in mind though, GCC is often smart enough to make that djnz optimization for you because it will notice that the loop variable is never used.

    But John, your conclusion is definitely correct: on hardware without a floating point ALU, there is no good solution.

    Now, based purely on the code you're showing, you don't actually need floating point.
    unsigned int i;
    for (i = 0; i < 300; ++i) {
        unsigned int hundreds = i / 100;
        unsigned int remainder = i % 100;
        print("\n%u %u.%02u", i, hundreds, remainder);
    }
    

    I know, you probably just simplified the code significantly for the sake of posting - but it's good to drop this in here in case anyone else runs across it.
Sign In or Register to comment.