10

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?

SuperSized
  • 789
  • 1
  • 8
  • 11

3 Answers3

12

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
  • 3,831
  • 1
  • 23
  • 18
  • 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 Oct 07 '09 at 03:21
  • 1
    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 Oct 07 '09 at 12:45
8

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

AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
3

Best PI/2 is not Math.PI/2!

In game development don't use the Math.PI constant, the loss of accuracy is negligible, you won't see the difference in the movement of your game objects... The performance is more important. Using the MathHelper.PiOver2 will save you a double division and a double to float conversion. This might seems to be very little help, but there are computationally intensive problems (particle systems) where the difference is significant.

Loránd Biró
  • 856
  • 6
  • 7