How can I work around the fact that in C++, sin(M_PI) is not 0?
- by Adam Doyle
In C++,
const double Pi = 3.14159265;
cout << sin(Pi); // displays: 3.58979e-009
it SHOULD display the number zero
I understand this is because Pi is being approximated, but is there any way I can have a value of Pi hardcoded into my program that will return 0 for sin(Pi)? (a different constant maybe?)
In case you're wondering what I'm trying to do: I'm converting polar to rectangular, and while there are some printf() tricks I can do to print it as "0.00", it still doesn't consistently return decent values (in some cases I get "-0.00")
The lines that require sin and cosine are:
x = r*sin(theta);
y = r*cos(theta);
BTW: My Rectangular - Polar is working fine... it's just the Polar - Rectangular
Thanks!
edit: I'm looking for a workaround so that I can print sin(some multiple of Pi) as a nice round number to the console (ideally without a thousand if-statements)
edit: In case anyone's curious, this was what I landed on:
double sin2(double theta) // in degrees
{
double s = sin(toRadians(theta));
if (fabs(s - (int)s) < 0.000001)
{
return floor(s + 0.5);
}
return s;
}
where toRadians() is a macro that converts to radians