Overview Of The Math Class

Overview

C# and XNA provide a great deal of commonly used methods for you to use. The System.Math class is a part of the C# framework, so it can be used even if you don't have XNA installed. This class includes the most common mathematical operations that you could want, including a definition for pi and e, as well as things like Sine, Cosine, Tangent, and a square root method.

The Math class is a static class, so to acess these methods, you use the class name Math, without actually creating an instance of a Math object. This is done like this:

double result = Math.Sqrt(14.0);

The PI and E Fields

pi and e are two constants that are commonly used in math.

Pi represents the ratio between the circumference of a circle and its diameter, and is approximately equal to 3.1415926536. It can be used in a variety of ways. Of particular importance is how it is used in measurement of angles. Many people are more used to measuring things in degrees, where 90 degrees is a right angle, and 360 degrees is a full rotation. The methods in the Math class, however, are done in radians. Radians is an alternative way of measuring angles, where a right angle is equal to pi / 2, and a full rotation is equal to 2 * pi. The MathHelper class provides easy methods for converting from radians to degrees, and from degrees to radians. The trigonometric methods in the Math class, such as Sin, Cos, and Tan, are all expecting angle measurements in radians, rather than degrees.

e is another interesting number, and has a variety of uses as well. e is approximately equal to 2.7182818285. While e comes up in math fairly frequently, it is not nearly as useful in a game development environment as pi. For now, it is enough to say that it is defined for you in the Math class in case you need it.

The Sqrt Method

The Sqrt method calculates the square root of a number.

(Remember a square root of a number is the number that when multiplied by itself equals the original number. So for instance, the square root of 81 is 9, because 9 * 9 = 81.)

Square roots are very useful in a wide variety of applications. It is key to understanding a great deal of more complicated math things, like finding the distance between two points.

The Sign Method

The Sign method is a way of determining whether a value is positive, negative, or equal to zero. Call the Sign method on a number (Math.Sign(17.4);) and the result will be an integer that is -1 if the value is less than 0, +1 if the value is greater than 0, or 0 if the value equals 0.

This can be used to easily check to see if a value is positive or negative like this:

if(Math.Sign(value) == 1) // Check to see if the value is positive
{
    // Do something in here if the value is positive
}
else if(Math.Sign(value) == -1) // Check to see if the value is negative
{
    // Do something in here if the value is negative
}

I'll be honest, though. In all likelyhood, this is no faster (and possibly somewhat slower) than this:

if(value > 0) // Check to see if the value is positive
{
    // Do something in here if the value is positive
}
else if(value < 0) // Check to see if the value is negative
{
    // Do something in here if the value is negative
}

The Abs Method

The Abs method tells you the absolute value of a number. The absolute value of a number is its distance from zero. This is also sometimes called its magnitude. In a sense, it gets rid of the negative sign of a number, if it has it. The absolute value of 4 is 4, and the absolute value of -4 is also 4.

The Sin, Cos, and Tan Methods

The Sin, Cos, and Tan methods correspond to the trigonometric functions sine, cosine, and tangent respectively. These methods are very commonly used in game development. Of particular interest is the fact that everything in your game is in floats, while these methods expect doubles and return doubles. You can give the methods floats, because they will automatically be converted to doubles, but you will need to cast the result back to a float in most cases, like this:

float result = (float)Math.Sin(1.245f);

The Asin, Acos, and Atan Methods

The Atan2 Method

The Sinh, Cosh, and Tanh Methods

The Min and Max Methods

The Min function returns the minimum of two numbers, and the Max function returns the maximum of two numbers. There is an overloaded method for each of the basic numeric data types, so whatever type of value you are putting in, you will get back out. (If you do the minimum of two ints, the result will be an int, and so on.)

One of the more effective ways to use this is in clamping, where you want to force a value into a particular range, like this:

int value = 30; // Assume 0-100 is a valid range for this.
// Do something in here that will cause the number to possibly go beyond those bounds.
value = Math.Min(value, 100); // If the number went higher than 100, it will be replaced with 100.
value = Math.Max(value, 0); // If the number went below 0, it will be replaced with 0.

The MathHelper class, however, provides a nicer way to clamp than this.

The Floor and Ceiling Methods

The Floor method takes a float, decimal, or double and finds the largest integer value less than or equal to it. The floor of 1.2 is 1, the floor of 1.9 is 1, the floor of -0.1 is -1, and so on. The Ceiling method does the same, except that it is the smallest number larger than or equal to it. The ceiling of 1.2 is 2, the ceiling of 1.9 is 2, the ceiling of -0.1 is 0, and so on.

The BigMul Method

When you do normal integer multiplication, you can run into overflow, where the resulting number is so big that an integer can't contain it any more. The calculated result will not be correct. The BigMul method takes two integer values and does the multiplication, resulting in a long, which has enough accuracy to hold the result.

This method probably won't be used too often in game development for a couple of reasons. First, most games won't involve multiplication with numbers big enough to cause overflow. Second, if you are running into this problem, you should be using the long type all the time anyway.

The place where this could be used most effectively is to check to see if overflow has occurred. This can be done with the following:

int number1 = 100000;
int number2 = 200000;
int resultAsInt = number1 * number2;
long resultAsLong = Math.BigMul(number1, number2);
if(resultAsInt != resultAsLong)
{
    // Overflow has occurred.
}

The DivRem Method

There are plenty of times where you want to do integer division, and also determine the remainder. As a refresher, If you do 10 / 3 as integer division, you get 3. The remainder is 1.

This the long way to do this is with something like this:

int dividend = 10;
int divisor = 3;
int quotient = 10 / 3;  // This will be 3
int remainder = 10 % 3; // This will be 1.

The DivRem method, however, let's you do this all in one step. The variable that is going to store the remainder is passed in as an output parameter, while the quotient is simply returned. The code above can be replaced with the following:

int dividend = 10;
int divisor = 3;
int remainder;
int quotient = Math.DivRem(dividend, divisor, out remainder);
// At this point, //remainder// will contain 1 and //quotient// will contain 3.

The Pow, Exp, and Log Methods

The Round Method

The IEEERemainder Method

The Truncate Method

What's Next?


troubleshoot64.png Having problems with this tutorial? Try the troubleshooting page!