# Why is sagemath real numbers arithmetic gives incorrect result?

I was using Sagemath for computation. There I was input "152.8-152.43" and gets something like "0.370000000000005". I tried to use RLF and RR too but I could not eliminate the extra number "5" at the end of the result. This raises no problem, since I do not that level of precision, but the number "5" at the end of the result just drives me upset. Why is it so? Is there anyway I can do to eliminate this problem? Matlab gave me the right answer. Is this some kind of weakness of Sagemath? I love Sagemath and intend to stick to it lifelong. But did I go wrong somewhere?

edit retag close merge delete

Sort by ยป oldest newest most voted

Real numbers have not, in general a finite binary representation. Therefore, the finite binary representation that you get by default when you type "152.8" is an _approximation_ of the real that you could represent exactly by using "1528/10'.

BTW :

    sage: QQ(152.8)-QQ(152.43)
37/100
sage: (15280/100-15243/100)
37/100
sage: (15280/100-15243/100).n()
0.370000000000000
sage: (152.8-152.43)-(15280/100-15243/100)
4.55191440096314e-15


which is compatible with the precision of the default binary representation of floats. If you want exact computations, use exact representations (which may or may not be finite...) : rationals, continued fractions. You can also use non-default representations with arbitrary representations.

HTH,

more

Thank you very much. I get it now.

( 2017-11-28 18:19:10 +0200 )edit