BlackWaspTM
.NET Framework
.NET 1.1+

.NET Math Library

The .NET framework includes a class named "Math", which provides a number of standard mathematical functions, using static methods, and mathematical values, using simple constants. This article describes all of the Math class members.

Math Class

An essential part of developing software is performing mathematical operations. To help, the .NET framework provides the Math class. This includes a number of standard mathematical functions and constants so that you do not need to implement or define them yourself. The functions are defined as a set of static methods, some of which work with many of the built-in numeric data types and some which limit the data types that can be used as parameters or returned from the methods.

The Math class' members can be roughly divided into the following seven categories:

  • Sign Operations. Methods that detect whether a value is positive or negative, or make negative values into their positive equivalents.
  • Multiplication and Division. Methods that multiply or divide values and calculate the remainder of a division.
  • Rounding. Methods that convert floating point values to integers and round values to a specified number of decimal places.
  • Exponential and Logarithmic Functions. Methods that work with logarithms, raise values to specified powers and find the square root of numbers.
  • Trigonometry. Methods that provide trigonometric functions, which calculate the geometry of triangles and the relationships between their sides and angles.
  • Comparison. Methods that compare two values to find which is larger or smaller.
  • Constants. Constants that provide standard values such as Pi (π) and the natural logarithm base (e), also known as Euler's number.

Sign Operations

The sign operations detect or modify the sign of a number. ie. Whether the value is positive or negative.

Abs

Abs calculates the absolute value of its input parameter. This is the magnitude of the number without regard to its sign. When applied to a positive number or zero, the return value is the same as the provided argument. For negative numbers, the sign is removed in the result, making a positive value. This method works with decimal, double, short, int, long, sbyte and float values.

The code below finds the distance between two integer values by subtracting one from the other and using the Abs function to ensure a positive result.

static void Main()
{
    int d;
    d = Distance(1, 10);    // d = 9
    d = Distance(10, 1);    // d = 9
    d = Distance(5, -5);    // d = 10
    d = Distance(-5, 5);    // d = 10
    d = Distance(-5, -5);   // d = 0
}

static int Distance(int a, int b)
{
    return Math.Abs(a - b);
}
7 October 2011