Ask Your Question
0

Why is sagemath real numbers arithmetic gives incorrect result?

asked 2017-11-28 08:24:06 +0100

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2017-11-28 09:03:24 +0100

Emmanuel Charpentier gravatar image

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,

edit flag offensive delete link more

Comments

Thank you very much. I get it now.

michaeldnguyen10 gravatar imagemichaeldnguyen10 ( 2017-11-28 18:19:10 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-11-28 08:24:06 +0100

Seen: 266 times

Last updated: Nov 28 '17