Re: sin (M_PI)




"Keith Thompson" <kst-u@xxxxxxx> wrote in message news:lnir8pbf1n.fsf@xxxxxxxxxxxxxxxxxx
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:
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.

Check out lisp.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

.



Relevant Pages

  • Re: sin (M_PI)
    ... and getting 1.22461e-16 instead of zero. ... significant figure you wish to round it, and whether you wish to round ... Rather than storing a numeric approximation to pi, ... this symbolic value yields exactly zero (if the sine function is ...
    (comp.lang.c)
  • Re: too many zeros and orbital mechanics.
    ... How do I tell Matlab not to do that? ... I can try round(e) which does round that to zero, ... exact value of zero, clear down to the least significant bit, you can ...
    (comp.soft-sys.matlab)
  • Rounding of integer divisions (was Re: linear interpolation / Assembler / ATMega32)
    ... The worst thing you may do is to unsignedify the number, round ... The function becomes dead around zero! ... int z, x, y; ... type casts and let the compiler get rid of the extra variables. ...
    (comp.arch.embedded)
  • Re: Rounding of integer divisions (was Re: linear interpolation / Assembler / ATMega32)
    ... The result is zero over ... Most high level languages round towards zero, ... Doing floored rounding makes ... I once designed a XY table that requires 24 bit math ...
    (comp.arch.embedded)
  • Re: .9 repeating
    ... regarding his mathematical theory and put them all together. ... | smallest round. ... | Its about the point next to zero on a number line. ... from MR to a rigorous theory, ...
    (sci.math)