Math Class in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The System.Math class offers many constant fields and static methods that you can use to do trigonometric, logarithmic, and other mathematical calculations. For example, the Pow method of the System.Math class can be used to raise a number to a power of x. Let's use the Pow method and the Math.PI field (returns the value of p, the ratio of a circle's circumference to its diameter) to calculate the area of a circle (dblRadius is the radius of a circle, and pi=3.14159265358979323846): 
 
            // Area of a Circle = πr2
double answer = Math.PI * Math.Pow(dblRadius,2};
 
Another constant, other than pi, is the natural logarithmic base or Euler constant, specified by the constant Math.E (e ˜ 2.7182818284590452354). The double Log method calculates the logarithm of a specified number in a specified base. The Log(double a, double newBase) method takes two parameters. The first is the number whose logarithm is to be found, and the second is the base of the logarithm.
 
Let's prove that log10e = 0.math-class-in-C-Sharp29448190325182765, which we already know from high school math lessons. 
 
            // log10e = 0.math-class-in-C-Sharp29448190325182765 ??? yes!
            answer = Math.Log(Math.E, 10);
 
The Math.Max and Math.Min return the larger and the smaller of two numbers passed in, respectively. They support almost all number types as parameters. Their overloads are shown in Listing 21.34. 
 
Listing 21.34: Math.Max and Math.Min Overloads 
 
byte Max(byte, byte);
decimal Max(decimal, decimal);
double Max(double, double);
short Max(short, short);
int Max(int, int);
long Max(long, long);
sbyte Max(sbyte, sbyte);
float Max(float, float);
ushort Max(ushort, ushort);
uint Max(uint, uint);
ulong Max(ulong, ulong);
byte Min(byte, byte);
decimal Min(decimal, decimal);
double Min(double, double);
short Min(short, short);
int Min(int, int);
long Min(long, long);
sbyte Min(sbyte, sbyte);
float Min(float, float);
ushort Min(ushort, ushort);
uint Min(uint, uint);
ulong Min(ulong, ulong);
 
You can use the Sqrt method to return the square root of a number. For example, the following code calculates the square root of 49, or 7. 
 
            answer = Math.Sqrt(49);
 
The Abs method returns the absolute value of a number (the positive value of a number regardless of its sign). For example, the following code returns the absolute value of -3, which is 3. 
 
            answer = Math.Abs(-3);
 
The Math.Abs method has many overloads matching common value types such as Int16, Int32, In32, Single, SByte, Decimal, and Double. 
The Sign method returns the sign of a number. The function returns one of three mathematical results. If the number is negative, Sign returns -1; if it's positive, Sign returns 1; if the number is equal to 0, Sign returns 0. 
 
The Round method rounds a number to the nearest whole number. Math.Round (banker's rounding or rounding to nearest) applies IEEE Standard 754, section 4. For example, the following code is used to round the number 5.499999. 
 
            answer = Math.Round(5.499999);
 
The answer would be 5. If you use Round to round a number that is exactly halfway between two numbers, such as 5.5, Round always returns the even number closest to the number. Thus, Math.Round(5.5) would return 6, but Math.Round(8.5) would return 8. 
 
Math.Round has another overload with which you can specify the number of digits beyond the decimal point in the returned value. In other words, it returns the number's nearest value with precision equal to the second parameter passed. If the value to round is exactly halfway between an even and an odd number (e.g., .45 with precision of 1), then the even number is returned. If the number of digits behind the decimal in the first parameter is less than the precision number in the second parameter, then the Round method returns the passed value untouched. Some examples are shown in Listing 21.35. 
 
Listing 21.35: Rounding with Precision 
 
            Math.Round(5.44, 1); // returns 5.4
            Math.Round(5.45, 1); // returns 5.4
            Math.Round(5.46, 1); // returns 5.5
            Math.Round(5.54, 1); // returns 5.5
            Math.Round(5.55, 1); // returns 5.6
            Math.Round(5.56, 1); // returns 5.6
 
You can use the Floor method to truncate a real number. Floor returns the largest whole number smaller than the original number. For example, use the following to return the floor of 4.8. 
 
            answer = Math.Floor(4.8);
 
The answer would be 4. Note that the Floor method may behave differently than you might expect for negative values. For example, Math.Floor(-4.8) returns -5. 
 
The Ceiling method does the opposite, returning the smallest whole number greater than the original. 
 
            answer = Math.Ceiling(4.8); // returns 5
 
The Math class contains a number of additional methods for making trigonometric and logarithmic calculations such as Sin, Asin, Sinh, Cos, Acos, Acosh, Tan, Atan, Tanh, Log, and Log10. 
 
In Listing 21.36 we use the Math.Sin function to output a sine wave cycle to the console. 
 
Listing 21.36: Outputting Sine Wave Values to Console 
 
using System;
class SineWaveToConsole
{
    private static string spaces(double val)
    {
        string SpaceString = new String(' ', ((int)(val * 10.0)) +  10);
        return SpaceString;
    }
    [STAThread]
    static void Main(string[] args)
    {
        for (float i = 0; i < Math.PI * 2.0F; i += 0.3F)
        {
            Console.WriteLine("The sine of {0,10:F} = {1,-10:F6}" + spaces(Math.Sin(i)) + "*", i, Math.Sin(i));
        }
        Console.ReadLine();
    }
}
 
The listing will output a numeric representation of a sine wave along with a text character graph (see Figure 21.3). Note the use of composite formatting to ensure that the sine value is trimmed to six digits beyond the decimal. 
 
Figure-21.3.gif
 
Figure 21.3: Output of Listing 21.36 
 
Conclusion
 
Hope this article would have helped you in understanding the Windows.Forms Namespace. See other articles on the website on .NET and C#.
 
visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all