Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Math vs. XNA MathHelper

Tags:

c#

math

pi

xna

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?

like image 331
SuperSized Avatar asked Oct 07 '09 02:10

SuperSized


3 Answers

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

like image 130
CoderTao Avatar answered Nov 14 '22 01:11

CoderTao


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

like image 28
AndreyAkinshin Avatar answered Nov 14 '22 03:11

AndreyAkinshin


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.

like image 27
Loránd Biró Avatar answered Nov 14 '22 01:11

Loránd Biró