Question

I am experiencing something weird with R recently. It can't get a sum write (even a simple one), I looked for any kind of precision issue but it did not seem it was the problem.

Any idea what could lead to that ?

> 0.1+0.2-0.4

Returns

> [1] -0.099999999999999977796
Was it helpful?

Solution

The answers to the question this will be closed as a duplicate of explains what is going on. But for a quick little thing hopefully this helps:

> options(digits = 22)
> .1 + .2 - 0.4
[1] -0.09999999999999997779554
> 0.1
[1] 0.1000000000000000055511
> 0.2
[1] 0.2000000000000000111022
> 0.4
[1] 0.4000000000000000222045

You can't represent 0.1 perfectly on a computer. It works with binary so only powers of 2 can be perfectly represented in decimal form. Some more examples:

> 1/2^2
[1] 0.25
> 1/2^3
[1] 0.125
> 1/2^4
[1] 0.0625
> 1/3
[1] 0.3333333333333333148296

OTHER TIPS

You can set the display precision with something like

options(digits=10)

But this doesn't affect the actual precision of the calculation - most non-integer-values (such as 0.1) cannot be represented exactly in floating point arithmetic.

See here for an introduction into floating point arithmetic:

http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top