Adam <ad**@sendnospa m.comwrote:
I am using the following code:
printf("%g", sin(M_PI))
and getting 1.22461e-16 instead of zero.
Does anyone have any idea why, and what I can do about it?
Pi is an irrational number, i.e. you can't write it down
exactly without giving an infinite number of digits (what-
ever number system you use). Computers can't deal with
irrational numbers very well (i.e. at all) since in a
computer you can only store a finite number of digits.
Thus what you use for pi is never the true value of pi
but an approximation. So you can't expect more that an
approximation of the value of sin of pi when you use an
approximation of pi to start with.
Whenever you use floating point numbers you must consider
that the computer only stores a limited number of (binary)
digits. In many cases the number of digits that can be
stored is less than the true number of digits of the
floating point number - rather obvious for irrational
numbers like pi, but even a simple looking number like 0.1
becomes a number with infinitely many digits when expressed
in binary (like 1/3 has an infinite number of digits when
written in decimal). Thus in many (if not most) cases you
do calculations with approximations only. And that's not
the end of it. E.g. function like sin are computed using
(clever) approximate algorithms (which tend to be a limi-
ted number of summands of an infinite sum). So you do ap-
proximate calculations of functions on approximate values.
And the result is, of course, that you end up with more or
less good approximate results. And when you think of it,
1e-16 is a rather good approximation for a 0 when you con-
sider the range [-1:1] of the sin function.
Thus if you do floating point calculations you have to be
aware of the approximate nature of such computations. And
you have to be aware that small errors due to the approxi-
mations can sum up considerably - if you aren't careful
you can end up with completely bogus results.
Regards, Jens
--
\ Jens Thoms Toerring ___
jt@toerring.de
\______________ ____________
http://toerring.de