Math

suggest change

The static class System.Math has the everyday math functions: absolute value, min/max, rounding, powers, roots, logarithms and trigonometry. Most methods take and return double, and many also have overloads for int, long, decimal and the other numeric types.

Related APIs:

The examples are C# 14 / .NET 10 file-based programs (dotnet run app.cs). Math is in the System namespace, which is imported implicitly.

Basics: Abs, Min, Max, Clamp, Sign

Console.WriteLine(Math.Abs(-7));
Console.WriteLine(Math.Max(3, 9));
Console.WriteLine(Math.Min(2.5, -1.0));
Console.WriteLine(Math.Clamp(150, 0, 100));
Console.WriteLine(Math.Clamp(-4.2, 0.0, 1.0));
Console.WriteLine(Math.Sign(-0.001));
Console.WriteLine(Math.Sign(0));
Console.WriteLine($"PI={Math.PI} E={Math.E} Tau={Math.Tau}");

try
{
    Console.WriteLine(Math.Abs(int.MinValue));
}
catch (OverflowException e)
{
    Console.WriteLine($"OverflowException: {e.Message}");
}
7
9
-1
100
0
-1
0
PI=3.141592653589793 E=2.718281828459045 Tau=6.283185307179586
OverflowException: Negating the minimum value of a twos complement number is invalid.

Things to know:

Rounding

There are four ways to turn a fractional number into a whole one:

double[] values = [2.5, 3.5, -2.5, 2.4, 2.6];
Console.WriteLine($"{"x",6} {"Round",6} {"AwayZ",6} {"Floor",6} {"Ceil",6} {"Trunc",6}");
foreach (var x in values)
{
    Console.WriteLine($"{x,6} {Math.Round(x),6} {Math.Round(x, MidpointRounding.AwayFromZero),6} " +
                      $"{Math.Floor(x),6} {Math.Ceiling(x),6} {Math.Truncate(x),6}");
}

Console.WriteLine(Math.Round(3.14159, 2));
Console.WriteLine(Math.Round(2.675m, 2));
Console.WriteLine(Math.Round(2.675m, 2, MidpointRounding.AwayFromZero));
Console.WriteLine(Math.Round(1234.5678, 2, MidpointRounding.ToZero));
Console.WriteLine((int)3.99);
Console.WriteLine((int)-3.99);
Console.WriteLine((int)Math.Round(3.99));
     x  Round  AwayZ  Floor   Ceil  Trunc
   2.5      2      3      2      3      2
   3.5      4      4      3      4      3
  -2.5     -2     -3     -3     -2     -2
   2.4      2      2      2      3      2
   2.6      3      3      2      3      2
3.14
2.68
2.68
1234.56
3
-3
4

The surprise for most people is the first row: Math.Round(2.5) is 2, not 3. By default Math.Round uses MidpointRounding.ToEven ("banker's rounding"): a value exactly halfway between two integers goes to the even one. This avoids a systematic upward bias when you round many values and add them up. If you want the "school" rule, pass MidpointRounding.AwayFromZero.

The other options:

double can't represent most decimal fractions exactly, so rounding money with double can give results that are off by a cent. Use decimal for money, and round only when displaying or storing a value. If you only need the rounded text, a format string such as x.ToString("F2") rounds too; see Numeric formats.

Integer division and remainder

Console.WriteLine(7 / 2);
Console.WriteLine(7 / 2.0);
Console.WriteLine(-7 / 2);
Console.WriteLine(7 % 3);
Console.WriteLine(-7 % 3);
Console.WriteLine(7.5 % 2);

(int q, int r) = Math.DivRem(17, 5);
Console.WriteLine($"17 = 5*{q} + {r}");

static int Mod(int a, int n) => ((a % n) + n) % n;
Console.WriteLine(Mod(-7, 3));
Console.WriteLine(Mod(-1, 24));

static int CeilDiv(int a, int b) => (a + b - 1) / b;
Console.WriteLine(CeilDiv(101, 25));
Console.WriteLine(Math.IEEERemainder(7, 3));

try
{
    Console.WriteLine(5 / int.Parse("0"));
}
catch (DivideByZeroException e)
{
    Console.WriteLine(e.Message);
}
Console.WriteLine(5.0 / 0);
Console.WriteLine(0.0 / 0);
3
3.5
-3
1
-1
1.5
17 = 5*3 + 2
2
23
5
1
Attempted to divide by zero.
∞
NaN

The rules:

Powers, roots and logarithms

Console.WriteLine(Math.Pow(2, 10));
Console.WriteLine(Math.Pow(2, 0.5));
Console.WriteLine(Math.Sqrt(144));
Console.WriteLine(Math.Cbrt(27));
Console.WriteLine(Math.Sqrt(-1));
Console.WriteLine(Math.Exp(1));
Console.WriteLine(Math.Log(Math.E));
Console.WriteLine(Math.Log10(1000));
Console.WriteLine(Math.Log2(1024));
Console.WriteLine(Math.Log(81, 3));
Console.WriteLine(Math.Log(0));
Console.WriteLine(Math.Pow(10, 20));
Console.WriteLine((long)Math.Pow(3, 39));
Console.WriteLine(IPow(3, 39));
Console.WriteLine(Math.Sqrt(3*3 + 4*4));
Console.WriteLine(double.Hypot(3, 4));

static long IPow(long b, int e)
{
    long result = 1;
    while (e > 0)
    {
        if ((e & 1) == 1) result = checked(result * b);
        e >>= 1;
        if (e > 0) b = checked(b * b);
    }
    return result;
}
1024
1.4142135623730951
12
3
NaN
2.718281828459045
1
3
10
4
-∞
1E+20
4052555153018976256
4052555153018976267
5
5

Notes:

Trigonometry

Trigonometric functions work in radians. Math.PI radians is 180 degrees.

static double ToRadians(double deg) => deg * Math.PI / 180;
static double ToDegrees(double rad) => rad * 180 / Math.PI;

Console.WriteLine(Math.Sin(ToRadians(30)));
Console.WriteLine(Math.Cos(ToRadians(60)));
Console.WriteLine(Math.Tan(ToRadians(45)));
Console.WriteLine(ToDegrees(Math.Asin(0.5)));
Console.WriteLine(double.DegreesToRadians(180));
(double sin, double cos) = Math.SinCos(Math.PI / 3);
Console.WriteLine($"sin={sin:F4} cos={cos:F4}");
// angle of vector (x, y), correct in all quadrants
foreach (var (x, y) in new[] { (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0) })
{
    Console.WriteLine($"({x,2}, {y,2}) -> Atan2 {ToDegrees(Math.Atan2(y, x)),5}  Atan {ToDegrees(Math.Atan(y / x)),4}");
}
0.49999999999999994
0.5000000000000001
0.9999999999999999
30.000000000000004
3.141592653589793
sin=0.8660 cos=0.5000
( 1,  1) -> Atan2    45  Atan   45
(-1,  1) -> Atan2   135  Atan  -45
(-1, -1) -> Atan2  -135  Atan   45
( 1, -1) -> Atan2   -45  Atan  -45

sin(30°) comes out as 0.49999999999999994 because Math.PI / 6 isn't exactly π/6. That is normal for floating-point math; round or format the result for display.

double.DegreesToRadians and double.RadiansToDegrees (.NET 8+) do the conversion for you. Math.SinCos computes both values in one call.

To get the angle of a vector or the direction from one point to another, use Math.Atan2(y, x). Math.Atan(y / x) can't tell (1, 1) from (-1, -1), as the table shows, and it divides by zero when x is 0. Atan2 returns an angle in the range -π to π.

Comparing floating-point numbers

double a = 0.1 + 0.2;
Console.WriteLine(a);
Console.WriteLine(a == 0.3);
Console.WriteLine(Math.Abs(a - 0.3) < 1e-9);

static bool NearlyEqual(double x, double y, double relTol = 1e-9, double absTol = 1e-12) =>
    Math.Abs(x - y) <= Math.Max(relTol * Math.Max(Math.Abs(x), Math.Abs(y)), absTol);

Console.WriteLine(NearlyEqual(a, 0.3));
Console.WriteLine(NearlyEqual(1e20 + 1e5, 1e20));
Console.WriteLine(NearlyEqual(1e-15, 0));

decimal d = 0.1m + 0.2m;
Console.WriteLine(d == 0.3m);

double sum = 0;
for (int i = 0; i < 10; i++) sum += 0.1;
Console.WriteLine(sum);
Console.WriteLine(sum.ToString("F2"));

double nan = Math.Sqrt(-1);
Console.WriteLine(nan == double.NaN);
Console.WriteLine(double.IsNaN(Math.Sqrt(-4)));
Console.WriteLine(double.IsInfinity(1 / 0.0));
Console.WriteLine(double.IsFinite(1e308 * 10));
Console.WriteLine(Math.Max(1.0, double.NaN));
Console.WriteLine(Math.MaxMagnitude(-5.0, 3.0));
Console.WriteLine(double.Epsilon);
Console.WriteLine(Math.BitIncrement(1.0) - 1.0);
0.30000000000000004
False
True
True
True
True
True
0.9999999999999999
1.00
False
True
True
False
NaN
-5
5E-324
2.220446049250313E-16

0.1, 0.2 and 0.3 have no exact binary representation, so 0.1 + 0.2 == 0.3 is false. Never compare computed double values with ==. Check that they are within a tolerance instead.

A fixed tolerance like 1e-9 breaks for very large numbers (where adjacent double values are far more than 1e-9 apart) and for very small ones. NearlyEqual uses a relative tolerance, scaled by the size of the numbers, plus an absolute tolerance for values near zero. Choose tolerances that fit your data.

The NaN rules:

double.Epsilon is the smallest positive double (about 5e-324). It is not the machine epsilon, and it's useless as a comparison tolerance. The gap between 1.0 and the next double is about 2.2e-16, which is what Math.BitIncrement(1.0) - 1.0 shows.

For a longer comparison of the types, see float, double, and decimal.

float and decimal

float f = MathF.Sqrt(2f);
Console.WriteLine(f);
Console.WriteLine(MathF.Sin(MathF.PI / 2));
Console.WriteLine(float.Sqrt(2f));
Console.WriteLine(Math.Sqrt(2));

decimal price = 19.99m;
decimal total = price * 3;
Console.WriteLine(total);
Console.WriteLine(Math.Round(total * 0.0825m, 2));
Console.WriteLine(Math.Abs(-1.5m));
Console.WriteLine(Math.Floor(-1.5m));
Console.WriteLine((decimal)Math.Sqrt((double)2m));
Console.WriteLine(1m / 3m);
Console.WriteLine(1m / 3m * 3m);
1.4142135
1
1.4142135
1.4142135623730951
59.97
4.95
1.5
-2
1.4142135623731
0.3333333333333333333333333333
0.9999999999999999999999999999

MathF mirrors Math for float, which avoids converting to double and back in graphics and game code. float.Sqrt does the same thing.

Math has decimal overloads only for Abs, Min, Max, Clamp, Sign, Round, Floor, Ceiling and Truncate. There's no decimal square root, power or logarithm, so you have to convert to double and accept the precision loss. decimal represents decimal fractions exactly, but it still can't represent 1/3.

Integer helpers

using System.Numerics;

Console.WriteLine(BigInteger.GreatestCommonDivisor(84, 36));
Console.WriteLine(Gcd(84, 36));
Console.WriteLine(Lcm(4, 6));
Console.WriteLine(int.IsPow2(64));
Console.WriteLine(int.Log2(1000));
Console.WriteLine(BitOperations.RoundUpToPowerOf2(1000u));
Console.WriteLine(BitOperations.PopCount(255u));
Console.WriteLine(BitOperations.TrailingZeroCount(48));
Console.WriteLine(Math.BigMul(int.MaxValue, int.MaxValue));
ulong high = Math.BigMul(ulong.MaxValue, 3UL, out ulong low);
Console.WriteLine($"high={high} low={low}");
Console.WriteLine(int.CopySign(5, -1));

static long Gcd(long a, long b)
{
    a = Math.Abs(a); b = Math.Abs(b);
    while (b != 0) (a, b) = (b, a % b);
    return a;
}
static long Lcm(long a, long b) => a / Gcd(a, b) * b;
12
12
12
True
9
1024
8
4
4611686014132420609
high=2 low=18446744073709551613
-5

Overflow and saturation

int big = int.MaxValue;
Console.WriteLine(big + 1);
try
{
    Console.WriteLine(checked(big + 1));
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);
}
double huge = 1e10;
Console.WriteLine((int)huge);
Console.WriteLine(int.CreateSaturating(huge));
Console.WriteLine(int.CreateTruncating(4_294_967_297L));
Console.WriteLine(Math.ScaleB(1.0, 10));
Console.WriteLine(Math.FusedMultiplyAdd(0.1, 10, -1));
Console.WriteLine(0.1 * 10 - 1);
-2147483648
Arithmetic operation resulted in an overflow.
2147483647
2147483647
1
1024
5.551115123125783E-17
0

Integer arithmetic silently wraps around by default: int.MaxValue + 1 becomes int.MinValue. Wrap the expression in checked(...) (or turn on <CheckForOverflowUnderflow> in the project) to get an OverflowException instead. See Integer overflow and Checked and Unchecked.

Converting an out-of-range double to int saturates to int.MaxValue on .NET 9 and later. Older runtimes returned platform-dependent values. To make the intent explicit, use the generic conversion methods:

Math.FusedMultiplyAdd(a, b, c) computes a * b + c with a single rounding. In the example it exposes the error that 0.1 * 10 - 1 hides: the exact product of the double closest to 0.1 and 10 is slightly more than 1.

Generic math

Since .NET 7, numeric types implement interfaces like INumber<T>, IRootFunctions<T> and ITrigonometricFunctions<T>. You can write one method that works for int, double, decimal and any other number type:

using System.Numerics;

Console.WriteLine(Sum([1, 2, 3, 4]));
Console.WriteLine(Sum([1.5, 2.25]));
Console.WriteLine(Sum([0.1m, 0.2m]));
Console.WriteLine(Mean([2, 4, 9]));
Console.WriteLine(Hypot(3f, 4f));

static T Sum<T>(T[] values) where T : INumber<T>
{
    T total = T.Zero;
    foreach (var v in values) total += v;
    return total;
}

static double Mean<T>(T[] values) where T : INumber<T> =>
    double.CreateChecked(Sum(values)) / values.Length;

static T Hypot<T>(T x, T y) where T : IRootFunctions<T> => T.Sqrt(x * x + y * y);
10
3.75
0.3
5
5

T.Zero, T.One, the operators and T.Sqrt are static abstract interface members, so the JIT generates specialized code for each type with no boxing. Pick the narrowest interface that has what you need: INumber<T> for arithmetic and comparison, IFloatingPointIeee754<T> for NaN and the trig and log functions. For more on constraints, see Generics.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents