tags:

views:

731

answers:

2

Ever since I needed to work with PI (3.1415...) in C# I have used Math.PI to get the value. Usually I would just use values like Math.PI/2.0 or 2.0*Math.PI, but now I have just noticed that XNA provides a MathHelper class. The nice thing about this is I can call MathHelper.PiOver2 and MathHelper.TwoPi, thus making an extremely trivial step even more trivial. ;-)

I assumed these two classes were interchangable, but I noticed that Math.PI/2.0 != MathHelper.PiOver2. I tried to research why this would be, but I found nothing. So, I thought I would try my luck here. With regards to using PI, are there any differences between the Math class and the MathHelper class? Is one preferred over the other? Or should I just leave well enough alone and just make sure to consistently use one or the other throughout my program?

+5  A: 

How not equal are they? If they are sufficiently close, this might just be the traditional problem that testing equality with floating points is near impossible.

Also, are they of the same type? My opinion was most gaming calculations were done with floats, where as Math.PI would be a double.

EDIT: MathHelper does indeed use floats

CoderTao
It's not really a problem with testing for equality since I found this out my looking at the difference, which should result to 0.000000000 if they were the same. Instead:MathHelper.Pi - Math.PI = 8.74227801261895E-08.This is certainly close enough for what I need to test for. I was just curious why they would be different. But, I agree, it must be a float vs. double problem.
SuperSized
That it's off by 10^-8 is probably indicative of the float->double difference in precision, specifically a float is only accurate to about 7-8 digits.
CoderTao
+2  A: 

Look to digit:

3,1415926535897900000000000000000 // Math.PI

3,1415930000000000000000000000000 // MathHelper.PI

3,1415926535897932384626433832795 // PI from Windows Calc


1,5707963267949000000000000000000 // Math.PI / 2

1,5707963705062900000000000000000 // MathHelper.PiOver2

1,5707960000000000000000000000000 // MathHelper.Pi / 2

1,5707963267948966192313216916398 // PI / 2 from Windows Calc


Explanation of problem: The loss in accuracy

Best PI / 2 = Math.PI / 2

DreamWalker
Pi to 10000 dp: http://joyofpi.com/pi.html
Richie Cotton
Thank you for good link
DreamWalker