Computers save floating point numbers as binary fractions. (Sums of digits with values of 1/2, 1/4, 1/8, 1/16, 1/32, etc.)
They can only save values that can be represented exactly with sums of those power-of-2 fractions exactly. All other decimal values are approximations.
Decimal numbers have the same issue. You can't represent 1/3 exactly in decimal. It comes out to 0.3333333333333 (repeating.)
In binary floating point, 0.1, 0.01, 0.001, and so on are all repeating binary fractions that are only approximate.
The other posters are suggesting using values that are ten-thousandths, and then scaling the result back to a decimal before doing other calculations on it.
That works because whole numbers are not subject to the same kinds of approximation errors that fractions are. By scaling your values up into whole numbers, you avoid error at each step in your calculation, and only use floating point at the end. You should use long integer (long) instead of int, to avoid overflowing the largest value that can be stored in an int (which is I believe 32767 for ints on Arduino, and about 2 billion for a long (16 bit vs 32 bit signed integer values.)
Mahmoud-elgeziry:
Hi all,
I am trying to write a code to calculate the position of the sun using my arduino, and I think I managed to have the code working, however, I have a certain variable in my code "n" that needs to incremented by a certain value each loop, I have this value at 0.0001, so the code for it is "n = n + 0.0001", and the arduino does increment, but not by 0.0001.
I figured that out when I found a significant error in the results at the end of the day, so I tracked back the code to find what was wrong, and I had the arduino display the values of "n" as it is incrementing it, and it was exactly 0.0001 when I had it display 4 decimal places, but when I had it display 7 decimal places, I noticed it is adding 0.0001016 instead of exactly 0.0001, that could be insignificant for a short time, but it gets accumulated and builds up to a HUGE error.
Does anybody know how to solve this?
here's my code: ZURB - Chop