Why does Sin[2.0 Pi]
evaluate to -2.44929 x 10^-16
and not 0.0
?
-
1$\begingroup$ This is a starting point reference.wolfram.com/language/tutorial/… $\endgroup$– dr.blochwaveCommented Feb 20, 2015 at 17:51
-
$\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$– user9660Commented Feb 20, 2015 at 17:52
-
1$\begingroup$ What Every Programmer Should Know About Floating-Point Arithmetic $\endgroup$– Martin EnderCommented Feb 20, 2015 at 18:14
-
$\begingroup$ Possible duplicate: (14122) $\endgroup$– Mr.WizardCommented Feb 20, 2015 at 18:24
2 Answers
If you use inexact arithmetic, you must accept that you will get inexact results, that is, an approximation to the exact result. 2.0
can be represent exactly as a machine float, but 2.0 Pi
cannot. Therefore, there is a small error in the argument given to Sin
which propagates during evaluation and produces the result you see. High precision numerics is something of an art. Mathematica supplies tools to make mastering that art easier than used to be, but you still have apply yourself to the mastery.
First you must understand the difference between machine precision arithmetic (CPU floating point) and Mathematica's own arbitrary precision arithmetic. You get the first by calling N
with one argument and the second by calling N
with two arguments, the second being the precision you want to maintain.
You can also activate arbitrary precision arithmetic by indicating the precision of all the numerical quantities appearing in a calculation. If no precision is explicitly indicated, you get machine CPU precision. Applied to the computation given in your example, these remarks play out as follows;
Sin[2.0 Pi] (* default machine precision *)
-2.44929*10^-16
N[Sin[2 Pi]] (* exact computation reduced to machine precision *)
0.
Sin[2.0`10 Pi] (* computation done with 10-digits as the precision goal *)
0.*10^-10
N[Sin[2.0`10 Pi]] (* the above reduced to machine precision *)
0.
The output from the 10-digit precision computation may look more precise than the default machine precision result, but it's not.
Abs[Sin[2.0`10 Pi]] < Abs[Sin[2.0 Pi]]
False
However, if 30-digit precision is requested
Abs[Sin[2.0`30 Pi]] < Abs[Sin[2.0 Pi]]
True
By using 2.0 instead of 2, you are using machine precision instead of symbolic outputs. Try this instead:
Sin[2 Pi]
That will return exactly 0.