1
$\begingroup$

Check the screen shot. Why I'm getting 999s? It is suppose to be 127,977.52

enter image description here

Thanks in advance,


Quick solution: AccountingForm[58156.48 + 69821.04, 16]

And thanks to Yves Klett

$\endgroup$
6
  • 1
    $\begingroup$ Welcome! The bugs tag is for confirmed bugs only. $\endgroup$ Commented Nov 24, 2014 at 17:16
  • $\begingroup$ Not to worry. What you are seeing is not a bug but a result of machine precision arithmetic. This is actually a duplicate of mathematica.stackexchange.com/q/5580/131. Also useful: floating-point-gui.de/basic $\endgroup$ Commented Nov 24, 2014 at 17:20
  • $\begingroup$ There are only two digits after decimal in the input, so ideally it output only 2 digits for additions or subtractions. Is there a way to get output like 127,977.52 in the above case? $\endgroup$ Commented Nov 24, 2014 at 17:24
  • $\begingroup$ Thanks checking those links, when I posted didn't saw those links. $\endgroup$ Commented Nov 24, 2014 at 17:25
  • $\begingroup$ The only way to "fix" this would be to use exact numbers. Most of the time this will not be neccessary however. $\endgroup$ Commented Nov 24, 2014 at 17:27

1 Answer 1

3
$\begingroup$

This is a problem for anything that uses machine precision floats, e.g. Mathematica, Matlab, C, etc.

Consider the simpler example $1/10$. In base 10, this fraction has the finite decimal expansion $$ 1/10 = 0.1 $$ But your machine would store this number (and all floats) in binary. The problem is, in binary $1/10$ has the infinite decimal expansion $$ 1/10 = \left(0.000\overline{1100}\right)_2 $$ This means your machine must to round (since it can't store infinite digits). This introduces error.

Now for your problem, we can see your decimals don't have a finite expansion in binary using RealDigits:

RealDigits[58156.48, 2] 
{{1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1}, 16} 
RealDigits[69821.04, 2] 
{{1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1}, 17} 

As Yves said in the comments, a fix in Mathematica is to avoid machine precision and use exact precision. Here I am forcing both numbers to have the first 20 digits correct:

58156.48`20 + 69821.04`20 // InputForm 
127977.52`20. 
$\endgroup$
1
  • $\begingroup$ Thanks 58156.4820 + 69821.0420 // InputForm That is exactly what I was looking for. $\endgroup$ Commented Nov 24, 2014 at 18:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.