Re: sin (M_PI)
- From: "Malcolm McLean" <regniztar@xxxxxxxxxxxxxx>
- Date: Thu, 12 Jul 2007 21:28:18 +0100
"Keith Thompson" <kst-u@xxxxxxx> wrote in message news:lnir8pbf1n.fsf@xxxxxxxxxxxxxxxxxx
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:Check out lisp.Adam said: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?
Presumably M_PI represents a value close to pi. It cannot represent pi
exactly, because pi is irrational. Given the nature of a sine wave, you
can expect sin(reasonable_approximation_to_pi) to be a reasonable
approximation to 0, and indeed that is what you are getting.
If you want to round the value, decide at which decimal place or
significant figure you wish to round it, and whether you wish to round
it up, down, or nearest. Then write code to do the rounding for you.
Or, if you're ambitious, you can do the calculation symbolically.
Rather than storing a numeric approximation to pi, store something
that explicitly refers to the symbol pi. Applying a sine function to
this symbolic value yields exactly zero (if the sine function is
implemented to work properly on symbolic values). Don't convert from
a symbolic value to a numeric value until you need to.
Note that these symbolic values can be arbitrarily complex; they're
(probably) basically expression trees, with facilities for evaluating
certain subexpressions non-numerically.
Implementing something like this would be a lot of work, but it's
useful enough that I'm sure it's already been done.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
.
- References:
- sin (M_PI)
- From: Adam
- Re: sin (M_PI)
- From: Richard Heathfield
- Re: sin (M_PI)
- From: Keith Thompson
- sin (M_PI)
- Prev by Date: Re: sin (M_PI)
- Next by Date: Re: sin (M_PI)
- Previous by thread: Re: sin (M_PI)
- Next by thread: Re: sin (M_PI)
- Index(es):
Relevant Pages
|