Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I work around the fact that in C++, sin(M_PI) is not 0?

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)

like image 269
Adam Avatar asked Apr 19 '10 21:04

Adam


2 Answers

What Every Computer Scientist Should Know About Floating-Point Arithmetic (edit: also got linked in a comment) is pretty hardcore reading (I can't claim to have read all of it), but the crux of it is this: you'll never get perfectly accurate floating point calculations. From the article:

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation.

Don't let your program depend on exact results from floating point calculations - always allow a tolerance range. FYI 3.58979e-009 is about 0.0000000036. That's well within any reasonable tolerance range you choose!

like image 136
AshleysBrain Avatar answered Sep 18 '22 17:09

AshleysBrain


Let's put it this way, 3.58979e-009 is as close to 0 as your 3.14159265 value is to the real Pi. What you got is, technically, what you asked for. :)

Now, if you only put 9 significant figures (8 decimal places) in, then instruct the output to also display no more, i.e. use:

cout.precision(8);
cout << sin(Pi);
like image 45
vladr Avatar answered Sep 19 '22 17:09

vladr