Hi!
I have some strange problem/misunderstanding with simple float numbers arithmetic. The following code snippet is printing some float variable f in the range from 0.00 to 4.00. The same variable is multiplied by 100 and printed as long type variable. The printed values are as expected till value of 2.40. The next number printed after 2.40 suprised me - it is 239 and than after 2.50 is 249 and so on... to the end.
Can someone explain why is that happening - I suppose it is something related with floating point precision or something..., is there a way to correct this? Thanks a lot!!
tomcuga:
I suppose it is something related with floating point precision or something.
You have answered your own question.
As to correcting it, some Arduinos like the due have a double precision floating point variable type. Be warned though that many, such as the Uno, appear to have a double type, but just use float for it.
Another solution is to use int or long for your math, treating your variables as fixed point and just add a decimal point when you display them.
GolamMostafa:
The following codes does give 240 from 240.00 in my MEGA; but, the OP's sketch gives 239 from 240.00 in my MEGA -- why? It could be something with OP's for() loop where float addition is being done which is never precise?
Just run OP's code with printing sufficient significant digits (I used 8) and you can see what happens. Do the same for yours
GolamMostafa:
Thank you for your reply,
Yes, It works directly when you put an value to f, but try to increment variable f from for example 2.2 to 2.4 by 0.1 increment and that doesn't work - at least on my hardware - Arduino Nano.
I tried also with double type, and with 4 decimal places - the same thing
wildbill> Thank zyou for your reply, I'm using multiplication by 100 and adding an decimal point - and that works actually, but in the for loop it doesn't work - actually it works till 2.3 number.
The last one is when one uses f=2.40; it's actually slightly bigger. Compare it with the result of the for-loop and you'll see that that one is slightly smaller.
GolamMostafa:
We are running after why the problem is there when the incremental value is 0.1.
Like @JCA34F already posted, it's a problem of the truncating conversion to an integral data type
and can be fixed by using rounding.
Usualy one would add .5 to the float to be converted, but here the values are so close,
that even a rounding to tenth works fine.
Thanks to all of you guys!! I learned something and that is great! In this exact situation I switched all my calculations to integer logic, actually long logic
But it is good to know what the problem is!