Adam wrote:
Hi,
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?
As the other responders have pointed out, this is to be expected. If you
had opened up your search engine, you surely would have found some close
references.
As you haven't said anything about your goals for modifying this
behavior, the suggestion about sinl(M_PIl) is as good as any, keeping in
mind that default Windows behavior is for long double to be simply an
alias for double.
Think about the steps you are taking here.
M_PI (not defined in std C) is likely a truncated decimal approximation
to the irrational value of pi.
The argument to sin() is at best the nearest binary value to the decimal
value. It could be as much as DBL_EPSILON larger or smaller than the
ideal value. A little application of high school math should help you
figure out how much difference this makes to the ideal value of sin().
If you are writing the code for a compiler to use in constant
propagation, say for a target processor like x87 which has some built-in
extra precision constants, you could take the position that you should
pick the closest of those built-in constants, when it satisfies the
demands of the C standard for closeness to the value in question. This
would enable the compiler to evaluate sin(M_PI) as 0. at compile time,
but then you would have a discrepancy against the behavior of values
generated at run time. Unless you want to write a sin() function which
searches for a match to certain multiples of the built-in pi before
evaluation. Where do you draw the line? pi/4,..., INT_MAX/4*PI ?
I understand there has been academic work on the precision attainable by
math functions including sin(). When people are building careers on this
subject, can you seriously ask "does anyone have any idea?"