In this article, we are going to describe the Math class in C#. The Math class in C# contains lots of useful static methods for performing all sorts of calculations. We’ll briefly describe all the methods in the library with some examples, so it will be quite a long article, but you can use it as a reference as well.
Let’s see what we have at our disposal.
Basic Math Functions
The first set of functions contains the most commonly used functions like the square root and calculating the maximum or minimum of two numbers.
Abs
The Abs
method returns the absolute value of the given argument:
Math.Abs(-1); // returns 1
Similar to many other methods we will see, there are several overloads of this method: It can accept a decimal, double, float, int, long, nint, sbyte or short, and returns the respective type.
Max
The Max
method returns the maximum value of the two arguments:
Math.Max(3.7, 1.8);// returns 3.7
It can accept a decimal, double, float, int, long, nint, sbyte, short, byte, uint, ulong, or ushort.
MaxMagnitude
The MaxMagnitude
method returns the larger magnitude of two doubles:
Math.MaxMagnitude(-10.0, 3.0); //returns -10
Min
The Min
method returns the minimum value of the two arguments:
Math.Min(5, 10); // returns 5
It can accept a decimal, double, float, int, long, nint, sbyte, short, byte, uint, long, or ushort.
MinMagnitude
The MinMagnitude
method returns the smaller magnitude of two doubles:
Math.MinMagnitude(-10.0, 3.0); //returns 3
BigMul
The BigMul
method produces the full product of two numbers.
As the result of multiplying two int numbers won’t fit into an int, the result is a long:
long result = Math.BigMul(Int32.MaxValue, Int32.MaxValue); // returns 4611686014132420609
There are also overloads to multiply long values and ulong values. In this case, the result will not fit into a long, so the result is spread of the return argument and an out argument, here we show it for the long case:
long lowerBits = 0, arg1 = long.MaxValue, arg2 = long.MaxValue; long higherBits = Math.BigMul(arg1, arg2, out lowerBits);
BitIncrement, BitDecrement
Returns the next larger (resp. smaller) double value that compares greater (resp. smaller) than the given argument:
bool lhsIsSmaller = Math.BitDecrement(1.123) < 1.123; // returns true bool rhsIsSmaller = Math.BitIncrement(1.123) > 1.123; // returns true
Cbrt
Returns the cube root of the given double argument:
Math.Cbrt(8.0); //returns 2
CopySign
Returns a value with the magnitude of the first, and the sign of the second double argument:
Math.CopySign(10.0, -2.0); // returns -10
DivRem
This method performs division with remainder, and returns both the quotient and the remainder as a tuple:
var (quotient, rem) = Math.DivRem(15, 7); // (quotient, rem) is (2, 1)
The input can be byte, int, long, nint, nuint, sbyte, short, uint, ulong, or ushort.
FusedMultiplyAdd
Returns (x*y)+z
, rounded as one operation. Contrary to doing these operations separately, the intermediate result is not rounded so this will give more accurate results. This can be beneficial in applications where the loss of precision due to many intermediate steps can be an issue:
Math.FusedMultiplyAdd(1.0, 2.0, 3.0); // returns 1*2 + 3 = 5
Both the input values and the output values are doubles.
IEEERemainder
This method returns the remainder resulting from the division of a specified number by another specified number, using the following formula. Both input and output are doubles:
IEEERemainder = dividend - (divisor * Math.Round(dividend / divisor))
The result is different from the %
operator:
Math.IEEERemainder(3, 2); //returns -1 var val = 3 % 2 // val is 1
ReciprocalEstimate, ReciprocalSqrtEstimate
This method returns an estimate of the reciprocal of a specified double
or the reciprocal square root of a given value:
Math.ReciprocalEstimate(2.0);// returns 0.5 Math.ReciprocalSqrtEstimate(4.0); // returns 1/(sqrt(4)) = 1/2 = 0.5
Unless it is an ARM64 architecture, this simply returns 1.0/value resp. 1.0/sqrt(value). In the case of an ARM64 architecture, it performs a Newton-Raphson iteration to calculate it, which might be more efficient.
Sign
This method returns the sign of a given number, i.e. returns -1 if the value is less than zero, 0 if it is zero, and +1 if it is greater than zero:
Math.Sign(-5.0); // returns -1
The input can be a double, int, float, decimal, long, nint, sbyte, or short. The output is always an int.
Sqrt
Returns the square root of a given double. When it is negative, it returns double.NaN
:
Math.Sqrt(4.0); // returns 2
Exponential and Logarithmic Functions
The Math class in C# provides lots of methods to work with exponentials and logarithms.
Exp
Returns the mathematical constant e
raised to the given power:
Math.Exp(1); // returns 2.71..
The input and output are double.
ILogB
This method returns the base 2 integer logarithm of a specified double number, i.e. (int)log2(val):
Math.ILogB(9.0); // returns 3
Log
Returns the natural logarithm of a given double value. When the given value is 0, it returns double.NegativeInfinity
and for negative values, it returns double.NaN
. You can also specify an optional argument to use another base:
Math.Log(Math.Exp(4.0));//returns 4 Math.Log(100, 10); // returns 2
Log10, Log2
Returns the 10 log resp. 2 log of a given double value. When the given value is 0, it returns double.NegativeInfinity
, and for negative values, it returns double.NaN
:
Math.Log10(1000); // returns 3 Math.Log2(16); // returns 4
Pow
Returns a specified number raised to another specified number. Both input and output are doubles:
Math.Pow(3.0, 3.0); // returns 3^3 = 27
ScaleB
Returns x*2^n, where x is a double and n is an integer. This can be done efficiently:
Math.ScaleB(3.0, 2); // returns 3.0*4 = 12
Trigonometric Functions
All the common (and less common) trigonometric methods are available in the Math
class as well:
Sin, Cos, Tan
These methods return the sine, cosine, or tangent resp. of a given double angle, measures in radians:
Math.Sin(Math.PI); // returns 0 Math.Cos(Math.PI); // returns -1 Math.Tan(Math.PI); // returns 0
Asin, Acos, Atan
These are the inverse sine, cosine, and tangent.
The Asin returns a value in the range-0.5PI till 0.5PI, double.NaN if the input is greater than 1, less than -1
The Acos returns a value in the range 0 till PI.
The Atan returns a value in the range -0.5PI till 0.5PI. If the given value is double.PositiveInfinity
, it returns 0.5*Math.PI
rounded to the nearest double:
Math.Asin(1); // returns Math.PI*0.5 Math.Acos(0); // returns Math.PI Math.Atan(double.PositiveInfinity); // returns 1.5707...
Sinh, Cosh, Tanh
These methods return the hyperbolic sine, cosine, and tangent of a given double value:
Math.Sinh(0); // returns 0 Math.Cosh(0.0); // returns 1 Math.Tanh(0.0); //returns 0
Asinh, Acosh, Atanh
These methods return the inverse hyperbolic sine, cosine, and tangent of a given double value:
Math.Asinh(0.0); // returns 0 Math.Acosh(1.0); // returns 0 Math.Atanh(0.0); // returns 0
Rounding and Related Functions
There are several different rounding related methods, which we organized under this section:
Ceiling
Returns the smallest integral value that is greater than or equal to the specified number. The input and output can be double or decimal:
Math.Ceiling(3.001); // returns 4 Math.Ceiling(1.0); // returns 1
Clamp
Returns the value clamped to a specified min and max value. If the value lies between the min and max, it simply returns the value. Otherwise, it returns either min or max. The input types can be decimal, double, float, int, long, nint, sbyte, short, byte, uint, ulong, or short:
Math.Clamp(0.0, -1.0, 2.0); // returns 0 Math.Clamp(-10.0, -1.0, 2.0); // returns -1 Math.Clamp(10.0, -1.0, 2.0); // returns 2
Floor
Returns the largest integral value that is smaller than or equal to the specified number. The input and output can be double or decimal:
Math.Floor(1.0); // returns 1 Math.Floor(1.3); // returns 1 Math.Floor(1.999); // returns 1
Round
Returns the closest integral value. The input type can be either double or decimal. One can also specify to how many decimal digits the specified value needs to be rounded to:
Math.Round(1.49); // returns 1 Math.Round(1.49, 1); // returns 1.5
Truncate
Returns an integral part of a given value. This is different than the other methods mentioned in this section, as it might round up or down depending on the sign of the value. The value itself can be double or decimal:
Math.Truncate(-2.2); // returns -2 Math.Truncate(2.2); // returns 2
Fields
There are several important mathematical constants that are represented as fields in the Math class in C#.
PI
The mathematical constant Pi (π):
public const double PI = 3.1415926535897931;
E
The mathematical constant e, i.e. the base of the natural logarithm:
public const double E = 2.7182818284590451;
Tau
This constant equals 2π. It has recently been introduced (since .NET 5):
public const double Tau = 6.2831853071795862;
Conclusion
We’ve seen that there are lots of mathematical methods in the Math class in C#, which can help you a lot if you are writing mathematical or scientific software.