# [R] calculating error

Gabor Grothendieck ggrothendieck at myway.com
Sun Sep 12 21:48:00 CEST 2004

```Branimir K. Hackenberger <hack <at> ffos.hr> writes:

:
: Could anybody explain this results?
:
: >sin(2*pi)
: -2.449213e-16         #should be zero
:
:
: >(10^16)*sin(log2(4)*pi)
: -2.449213             #should be zero too
:
:
: and explain what to do to correct this events?

Someone else has already explained why this is.

In terms of what you can do, in general, you have to keep
finite precision in mind when performing computer calculations
using floating point representations.

Sometimes there are tricks.  If you know that the result or
an intermediate result will be integer then if the error
is sufficiently small you can round it at that point:

R> round(sin(2*pi))
[1] 0

R> (10^16)*round(sin(log2(4)*pi))
[1] 0

If exact arithmetic is required you may need to use a symbolic
mathematics package capable of exact arithmetic.  There are both
free, e.g. yacas, and commercial ones, e.g. mathematica, maple.
For example, in yacas:

In> Sin(2*Pi);
Out> 0;
In> (10^16)*Sin(IntLog(4,2)*Pi)
Out> 0;

```