#include <REGX52.h> unsigned char i; float x; void main() { x=0; for(i=1;i<=30;i++) {x+=1.3;} }
This should ideally produce an output of x=39.
But in debugger the value is shown as x=38.999999. What could be the issue?
You can never precisely express decimal 1.3 in binary. That's it.
You can never precisely express decimal 1.3 in binary.
That's not true. You can represent anything in binary, but you might not be able to do so directly.
Even my very old Casio calculator could cope with 1.3; it was just necessary to do so as a fraction. As far as I know, those calculators used a traditional 4 bit processor.
How can I represent 1.3 as a fraction? Or is there any other workaround?
"How can I represent 1.3 as a fraction?"
Quite basic math. 13/10.
So suddenly you can do the add.
13 13 13 13 13 390 39 == + == + == + == + == ... = === = == = 39 10 10 10 10 10 10 1
Lots of math problems requires the use of symbolic manipulation because numerical methods will produce very problematic intermediate results.
In the end, this isn't something you can expect to solve by a short debate in this forum.
Precision, resolution, numerical stability, cancellation,... are a significant part of several courses at the university. A 10 minute answer on a forum isn't enough to make you a great programmer - you need to invest a huge amount of own time too. So start by getting some books on numerical methods etc.
I guess this is why the librarty en.wikipedia.org/.../C_mathematical_functions includes round()
No, the round() function has more general use.
But this is why the normal printf() function tries to print floating point numbers with less number of value digits than the full number of bits in the float mantissa can represent - the last bits of the mantissa are often garbage.
It's just that cancellation errors and numerical stability of formulas will affect how many of the least significant bits that are garbage so printf() can't know how many "safe" digits that remains in the floating point number.
Not even with double or extended precision floating point arithmetic will it be possible to guarantee a fixed number of "safe" digits if a too numerically unstable formula has been used. Bad cancellation can throw away all value digits in a single step.