Miscalculations

Hey guys,
I am seriously baffled by the bug I am getting right now.
So I have the following code:

driveStepsLeft = round( ( ( (float)distance * (float)4096 ) / distancePerRev ) );

distance = 2300 and distancePerRev = 235.6

so I should end up with 39986 right ?

but instead I get -25550 ?!?!?!?!

The calculation is performed hundreds of times, and works before this point (where the program stops running cause the negative breaks the following code). I tried two boards, a mega and an uno, still the same result, in the same spot. I am sure I must be doing something wrong somewhere, but I have no clue what would cause this. I have also checked free memory before this point, and that's all fine, so what's happening ?

Regards,
TonyStark2

Please provide the data types for all those variables.

However if you are getting negative numbers it sounds like overflow.

Sorry,
driveStepsLeft is an integer
distance is an integer
distancePerRev is a float

Thanks

2300 * 4096/235.6 = 39986 on my calculator

This will overflow a normal int and give a negative result. A long might be the correct type to use here.

Yeah sorry, just fixed that calculation.
Yeah, I changed driveStepsLeft to unsigned long int. It works now :slight_smile:
All down to bad code design :S
Thanks guys

TonyStark2:
driveStepsLeft = round( ( ( (float)distance * (float)4096 ) / distancePerRev ) );

distance = 2300 and distancePerRev = 235.6

so I should end up with 39986 right ?

Yes. Which doesn't fit into an int. Maximum value: 32767.

39986 - 65536 = -25550

Which is what you got.

Read the link I posted.

Either use floats for the whole thing, or use ints and longs. Using both is just creating trouble and overhead for yourself.

And if distancePerRev is a constant, determine what 4096/distancePerRev is, and use that.

Be warned that the round macro turns the number into long:

#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

BTW, a cunning attempt to confuse us by changing the original post:

Here we were, proving that 7563 was in fact wrong, when you altered it. :stuck_out_tongue: