TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Math Class

These C# examples demonstrate the Math type. This type offers many mathematical functions ready to deploy.

Math is a class in the System namespace.

The .NET Framework provides many built-in mathematical methods. These are easier to use than custom expressions. They are tested and easy to access.

Methods. 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

C# program that uses Math method

using System;

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

Output

0.598472144103957

Abs. The Abs method computes absolute values. Since absolute values are always positive numbers, this example may help make you happier. As with other Math methods, the built-in logic makes programs simpler.

Abs

Max, min. 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. 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.

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. 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.

RoundTruncate

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

CeilingFloor

Sign. Is a number positive or negative? The Math.Sign method will help you determine this in a declarative way. Math.Sign accepts many numeric types as arguments. It returns one of three values: -1, 0 or 1.

Info: The result -1 means negative. Zero means the number is zero. And 1 means it is positive.

Next: This program demonstrates the Math.Sign method with ints and doubles as arguments.

C# program that uses Math.Sign method

using System;

class Program
{
    static void Main()
    {
	int a = Math.Sign(-5);
	int b = Math.Sign(5);
	int c = Math.Sign(0);

	Console.WriteLine(a);
	Console.WriteLine(b);
	Console.WriteLine(c);

	a = Math.Sign(-5.5);
	b = Math.Sign(5.5);

	Console.WriteLine(a);
	Console.WriteLine(b);
    }
}

Output

-1
1
0
-1
1

Implementation: Sign is implemented with branch statements that test the formal parameter against zero.

Zero: Sign returns 0 when the argument is 0, which reflects the fact that zero is neither positive nor negative.

Constants. 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.

PI

Exp. 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.

C# program that uses Exp method

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. 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.

C# program that uses IEEERemainder

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. 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

C# program that calls BigMul

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

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.

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.

Out

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

Long

C# program that calls DivRem method

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. 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf