Hi,
I just want to make very simple operations, and it doesn’t work.
The result of the attached operation (in the last line i) should be simply zero, and I have 9. 10 -13 instead of zero ! …
Please help.
a = 5306.47
b = 4
c = 1182.54
d = 50.26
e = 0
f = 377.11
g = c + d + e + f
h = 3700.56
i = a + b - g - h
Machine precision numbers are not exact so there will always be rounding errors. This is not something specific to Wolfram language. If you want exact results, use exact numbers.
a = Rationalize@5306.47
b = 4
c = Rationalize@1182.54
d = Rationalize@50.26
e = 0
f = Rationalize@377.11
g = c + d + e + f
h = Rationalize@3700.56
i = a + b - g - h
(* 0 *)
Thank you very much!
So does it means that for financial computations, it is recommended to always enclose the inputs numbers with the Rationalize[] function?
It would depend on what “financial computations” are being performed. Machine precision is about 16 decimal digits which should be sufficient. As Marvin showed, you can always use Chop to convert small values to 0.
Don’t mix integers with reals, Rationalize[] is an ovekill because there is AccountingForm[], a formatter, with other words
Clear[a, b, c, d, e, f, h]
a = 5306.47;
b = 4.;
c = 1182.54;
d = 50.26;
e = 0.;
f = 377.11;
h = 3700.56`;
In[51]:= c + d + e + f // AccountingForm
Out[51]//AccountingForm= 1609.91
In[52]:= a + b - g - h // AccountingForm
Out[52]//AccountingForm= 0.
..? Thanks for the proposal, but this following code doesn’t give the expected result (0) on my side …
Clear[a, b, c, d, e, f, h]
a = 5306.47
b = 4.
c = 1182.54
d = 50.26
e = 0.
f = 377.11
g = c + d + e + f // AccountingForm
h = 3700.56
i = a + b - g - h // AccountingForm
That is because AccountingForm is not computable (like MatrixForm, TableForm…). It is for display purposes only. It can only be used on the final result.
Accuracy can be nailed on input, still output needs to be stripped by a formatter
Clear[a, b, c, d, e, f, h, g]
a = 5306.47``2;
b = 4.``2;
c = 1182.54``2;
d = 50.26``2;
e = 0.``2;
f = 377.11``2;
h = 3700.56``2;
g = c + d + e + f
Out[9]= 1609.9
In[14]:= a + b - g - h
Out[14]= 0.*10^-2
In[12]:= N[a + b - g - h]
Out[12]= 0.
In[13]:= AccountingForm[a + b - g - h]
Out[13]//AccountingForm= 0.