C# Math

Math

Arithmetic expressions can implement mathematical functions. But the .NET Framework provides many built-in Math methods. These are easier to use than custom expressions. They are tested and easy to access.

.NET

Methods

Piece of computer software: a program

As an introduction, we examine a program that uses the Math.Sin method. This method returns the sine of a specified angle, measured in radians. Most of the Math methods can be used with this syntax form.

Tip:The System namespace must be included at the top of the file to directly access the Math type.

Based on:

.NET 4.5

Program that uses Math method: C#

using System;

class Program
{
    static void Main()
    {
	// Use Math method.
	double sin = Math.Sin(2.5);
	Console.WriteLine(sin);
    }
}

Output

0.598472144103957
Plus

Absolute values. Next, we present information about how to find absolute values in the C# language. Since absolute values are always positive numbers, this example may help make you happier.

Abs

Signs:Is a number positive or negative? The Math.Sign method will help you determine this in a declarative way.

Sign

Minimum and maximum. Suppose you have two numbers and want to use an expression to find the smaller or the larger of the two. Math.Max and Min provide this functionality. With them we declaratively find minimums and maximums.

MaxMin

Exponents

Sqrt function

You can compute the square root of a number with the Math.Sqrt method. We also introduce a way to improve performance of nearly all Math methods. A lookup table eliminates repeated operations.

Sqrt

Tip:Using a lookup table to cache the result of Math methods is a beneficial performance enhancement.

Pow

Powers and logs. What is three to the power of two? Instead of computing this in your head, you could use the C# language and Math.Pow method. It handles exponents. For scientific problems the Pow method is useful.

PowLog

Cos, Sin, Tan

Note

You can use the trigonometric identities in your C# program with the Math.Cos, Math.Sin, and Math.Tan methods. Also, there are hyperbolic and inverse methods available for your use.

Cos, Sin, Tan

Rounding

Should you round 1.5 to 2 or 1? The Math.Round method helps us decide. We should use a formalized system for your rounding, to make it consistent. Math.Truncate, on the other hand, returns the integral part with no rounding.

RoundTruncateFloor numeric function

Ceiling and floor:In mathematics, these don't have much to do with actual buildings. They compute the next highest or lowest integer.

CeilingFloor

Constants

Mathematical constant e: Euler's number

The mathematical constant E is available in the Math type as well. This is not the most useful article, but it contains an interesting anecdote about Google. Also, the Math.Exp method internally uses the E constant.

E Constant

PI constant. In the C# language, the simplest way to acquire pi is with the Math.PI constant in the System namespace. This yields a double type of the maximum number of digits allowed by doubles.

PIPi equation

Exp

Math written on chalkboard

Math.Exp computes values of the exponential function. To apply the exponential function, we either use Math.Pow to raise E to a specified power, or call Math.Exp with the exponent as an argument. Exp is part of the Math class.

Here:To begin, this program calls the Math.Exp method and then calls the Math.Pow method such that they have equivalent results.

Note:The Math.Exp always uses Math.E (e) as the specified number. The results of these two method calls are the same.

Program that uses Exp method: C#

using System;

class Program
{
    static void Main()
    {
	// Compute e ^ 2.
	double a = Math.Exp(2);
	double b = Math.Pow(Math.E, 2);

	// Write results.
	Console.WriteLine(a);
	Console.WriteLine(b);
    }
}

Output

7.38905609893065
7.38905609893065

IEEERemainder

Percentage symbol

The IEEERemainder method returns a remainder of 1 for the arguments 4, 3. This is the same result as the modulo expression.
But with the arguments 3
and 4,
it returns a remainder of -1. The modulo expression meanwhile returns the value 3.

Here:We see that for IEEERemainder, two positive numbers can have a negative remainder.

Tip:This occurs when the first number is smaller than the second number. In many cases, the modulo operator returns the same result.

Program that uses IEEERemainder: C#

using System;

class Program
{
    static void Main()
    {
	double a = Math.IEEERemainder(4, 3);
	Console.WriteLine("Part 1");
	Console.WriteLine(a);
	Console.WriteLine(4 % 3);

	double b = Math.IEEERemainder(3, 4);
	Console.WriteLine("Part 2");
	Console.WriteLine(b);
	Console.WriteLine(3 % 4);
    }
}

Output

Part 1
1
1
Part 2
-1
3

BigMul

Star, asterisk character

Math.BigMul multiplies two large integers.
With regular multiplication,
as with the star operator,
the result may overflow. BigMul avoids this problem. It returns a long. It ensures the result is correctly computed and stored.

Here:This program's goal is to multiply the int.MaxValue value (2147483647) by itself. If we call Math.BigMul, the result will be correct.

But:If we just use the * operator, the result will overflow and must be compiled in an unchecked context.

Uncheckedint.MaxValue
Program that calls BigMul: C#

using System;

class Program
{
    static void Main()
    {
	// Call BigMul.
	long product1 = Math.BigMul(int.MaxValue, int.MaxValue);
	// Use multiplication operator.
	long product2 = unchecked(int.MaxValue * int.MaxValue);

	// Display values.
	Console.WriteLine(product1);
	Console.WriteLine(product2);
    }
}

Output

4611686014132420609
1
Concept: a discussion topic

If you remember math class, when you multiply two large numbers like 2147483647 you should not get 1. This makes no sense. Instead, you should get a larger number—something hard to remember.

Note:If you query Google for 2147483647 squared, it will give you the correct result.

So:You should probably use BigMul anywhere you are multiplying large integers.

MultiplyOverflowExceptionInt

DivRem

Math.DivRem divides two numbers and returns the remainder. With the division operator we do not get the remainder in a separate variable. But with Math.DivRem we compute the quotient and the remainder. We can store them separately.

Out keyword

This program divides the value 1000 by the value 300. Because the 300 can go into the 1000 three times, you get the result of 3. However, there is 100 left over. This is returned by the out parameter in the Math.DivRem method.

Tip:The out parameter in the DivRem method is always assigned when DivRem returns. It will be ready to use.

OutLong type

Long:The Math.DivRem method can also accommodate much larger numbers stored as longs.

Long
Program that calls DivRem method: C#

using System;

class Program
{
    static void Main()
    {
	const int a = 1000;
	const int b = 300;
	int result;

	int quotient = Math.DivRem(a, b, out result);

	Console.WriteLine(quotient);
	Console.WriteLine(result);
    }
}

Output

3
100

Summary

Framework: NET

Instead of implementing these functions yourself, I suggest using the Math type. It has many public static methods: these are helpful. With these methods, you may be able to improve the quality of your code.


C#: Number