Mathematics in C# 


If you consider it in the purest sense of a computer language like C, C++, Pascal, Visual Basic, and Java, etc, C# doesn't have its own builtin support for mathematics. It must borrow this functionality either from other libraries or from other language. Fortunately, all of this is particularly easy. To perform the basic algebraic and geometric operations in C#, you can use methods of the Math class of the .NET Framework. As seen in the previous lesson, you can also take advantage of Visual Basic's very powerful library of functions. This library is one of the most extended set of functions of various area of business mathematics. In Lesson 1, we saw different ways to declare a variable of a numeric type. Here are examples: using System; class Program { static int Main() { short sNumber; int iNumber; double dNumber; decimal mNumber; return 0; } }
One of the primary rules to observe in C# is that, after declaring a variable, before using it, it must have been initialized. Here are examples of initializing variables: using System; class Program { static int Main() { short sNumber = 225; int iNumber = 847779; double dNumber = 9710.275D; decimal mNumber = 35292742.884295M; Console.WriteLine("Short Integer: {0}", sNumber); Console.WriteLine("Integral Number: {0}", iNumber); Console.WriteLine("DoublePrecision: {0}", dNumber); Console.WriteLine("Extended Precision: {0}", mNumber); return 0; } } This would produce: Short Integer: 225 Integral Number: 847779 DoublePrecision: 9710.275 Extended Precision: 35292742.884295 Press any key to continue . . . When initializing a variable using a constant, you decide whether it is negative, 0 or positive. This is referred to as its sign. If you are getting the value of a variable some other way, you may not know its sign. Although you can use comparison operators to find this out, the Math class provides a method to check it out for you. To find out about the sign of a value or a numeric variable, you can call the Math.Sign() method. It is overloaded in various versions whose syntaxes are: public static int Sign(sbyte value); public static int Sign(short value); public static int Sign(int value); public static int Sign(long value); public static int Sign(sbyte value); public static int Sign(double value); public static int Sign(decimal value); When calling this method, pass the value or the variable you want to consider, as argument. The method returns:
Here are examples of calling the method: using System; class Program { static int Main() { short sNumber = 225; int iNumber = 847779; double dNumber = 9710.275D; decimal mNumber = 35292742.884295M; Console.WriteLine("Number: {0} => Sign: {1}", sNumber, Math.Sign(sNumber)); Console.WriteLine("Number: {0} => Sign: {1}", iNumber, Math.Sign(iNumber)); Console.WriteLine("Number: {0} => Sign: {1}", dNumber, Math.Sign(dNumber)); Console.WriteLine("Number: {0} => Sign: {1}\n", mNumber, Math.Sign(mNumber)); return 0; } } This would produce: Number: 225 => Sign: 1 Number: 847779 => Sign: 1 Number: 9710.275 => Sign: 1 Number: 35292742.884295 => Sign: 1 Press any key to continue . . .
As reviewed in Lesson 1, when dealing with a floatingpoint number, it consists of an integral side and a precision side; both are separated by a symbol which, in US English, is the period. In some operations, you may want to get the integral side of the value. The Math class can assist you with this. To get the integral part of a decimal number, the Math class can assist you with the Trancate() method, which is overloaded in two versions whose syntaxes are: public static double Truncate(double d); public static double Truncate(double d); When calling this method, pass it a number or a variable of float, double, or decimal type. The method returns the int side of the value. Here is an example of calling it: using System; class Program { static int Main() { float number = 225.75f; Console.WriteLine("The integral part of {0} is {1}\n", number, Math.Truncate(number)); return 0; } } This would produce: The integral part of 225.75 is 225 Press any key to continue . . .
If you have two numbers, you can find the minimum of both without writing your own code. To assist you with this, the Math class is equipped with a method named Min. This method is overloaded in various versions with each version adapted to each integral or floatingpoint data type. The syntaxes are: public static byte Min(byte val1, byte val2); public static sbyte Min(sbyte val1, sbyte val2); public static short Min(short val1, short val2); public static ushort Min(ushort val1, ushort val2); public static int Min(int val1, int val2); public static uint Min(uint val1, uint val2); public static float Min(float val1, float val2); public static long Min(long val1, long val2); public static ulong Min(ulong val1, ulong val2); public static double Min(double val1, double val2); public static decimal Min(decimal val1, decimal val2); Here is an example of calling the method: using System; class Program { static int Main() { int number1 = 8025; int number2 = 73; Console.WriteLine("The minimum of {0} and {1} is {2}", number1, number2, Math.Min(number1, number2)); return 0; } } This would produce: The minimum of 8025 and 73 is 73 Press any key to continue . . .
As opposed to the minimum of two numbers, you may be interested in the higher of both. To help you find the maximum of two numbers, you can call the Max() method of the Math class. It is overloaded in various versions with one of each type of numeric data. The syntaxes of this method are: public static byte Max(byte val1, byte val2); public static sbyte Max(sbyte val1, sbyte val2); public static short Max(short val1, short val2); public static ushort Max(ushort val1, ushort val2); public static int Max(int val1, int val2); public static uint Max(uint val1, uint val2); public static float Max(float val1, float val2); public static long Max(long val1, long val2); public static ulong Max(ulong val1, ulong val2); public static double Max(double val1, double val2); public static decimal Max(decimal val1, decimal val2); Here is an example of calling the method: using System; class Program { static int Main() { int number1 = 8025; int number2 = 73; Console.WriteLine("The maximum of {0} and {1} is {2}", number1, number2, Math.Max(number1, number2)); return 0; } } This would produce: The maximum of 8025 and 73 is 8025 Press any key to continue . . .
In Lesson 1, we saw how to declare variables of integral, floatingpoint, and string types. We also saw how to initialize the variables. If you have a program with mixed types of variables, you may be interested in converting the value of one into another. Again, in Lesson 1, we saw how much memory space the variable of each data type required in order to hold its value. Here is a summary of what we learned:
As you can see, a value held by a Byte variable can fit in the memory reserved for an int variable, which can be carried by a long variable. Thanks to this, you can assign a Byte value to an int variable, or an int variable to a long variable. Also, based on this, because the memory reserved for an int variable is larger than the one reserved for a double variable, you can assign a variable of the former to a variable of the latter. Here is an example: using System; class Program { static int Main() { int iNumber = 2445; double dNumber = iNumber; Console.WriteLine("Number = {0}", iNumber); Console.WriteLine("Number = {0}\n", dNumber); return 0; } } This would produce: Number = 2445 Number = 2445 Press any key to continue . . . This characteristic is referred to as implicit conversion.
Because of memory requirements, the direct reverse of implicit conversion is not possible. Since the memory reserved for a short variable is smaller than that of an int, you cannot assign the value of an int to a short variable. Consider the following program: using System; class Program { static int Main() { int iNumber = 168; short sNumber = iNumber; Console.WriteLine("Number = {0}", iNumber); Console.WriteLine("Number = {0}\n", sNumber); return 0; } } This would produce the following error: Cannot implicitly convert type 'int' to 'short'. Value casting consists of converting a value of one type into a value of another type. For example, you may have an integer value and you may want that value in an expression that expects a short. Value casing is also referred to as explicit conversion. To cast a value or a variable, precede it with the desired data type in parentheses. Here is an example: using System; class Program { static int Main() { int iNumber = 168; short sNumber = (short)iNumber; Console.WriteLine("Number = {0}", iNumber); Console.WriteLine("Number = {0}\n", sNumber); return 0; } } This would produce: Number = 168 Number = 168 Press any key to continue . . . When performing explicit conversion, you should pay close attention to the value that is being cast. If you want an integer value to be assigned to a short variable, the value must fit in 16 bits, which means it must be between 32768 and 32767. Any value beyond this range would proceed an unpredictable result. Consider the following program: using System; class Program { static int Main() { int iNumber = 680044; short sNumber = (short)iNumber; Console.WriteLine("Number = {0}", iNumber); Console.WriteLine("Number = {0}\n", sNumber); return 0; } } This would produce: Number = 680044 Number = 24684 Press any key to continue . . . Notice that the result is not reasonable.
In Lesson 6 and Lesson 17, we saw that each C# data type, which is adapted from a .NET Framework structure, was equipped with a ToString() method that could be used to convert its value to a String type. We didn't address the possibility of converting a value from one primitive type to another. To support the conversion of a value from one type to another, the .NET Framework provides a class named Convert. This class is equipped with various static methods; they are so numerous that we cannot review all of them. Remember that each primitive data type of the C# language is typedefined from a .NET Framework structure as follows:
To adapt the Convert class to each C# data type, the class is equipped with a static method whose name starts with To, ends with the .NET Framework name of its structure, and takes as argument the type that needs to be converted. Based on this, to convert a decimal number of a double type to a number of int type, you can call the ToInt32() method and pass the double variable as argument. Its syntax is: public static int ToInt32(double value); Here is an example: using System; class Program { static int Main() { double dNumber = 34987.68D; int iNumber = Convert.ToInt32(dNumber); Console.WriteLine("Number: {0}", dNumber); Console.WriteLine("Number: {0}", iNumber); return 0; } }
The decimal numeric system counts from negative infinity to positive infinity. This means that numbers are usually negative or positive, depending on their position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, its absolute value is its positive equivalent. For example, the absolute value of 12 is 12, while the absolute value of 12 is 12. To get the absolute value of a number, the Math class is equipped with a method named Abs, which is overloaded in various versions. Their syntaxes are: public static sbyte Abs(sbyte value); public static short Abs(short value); public static int Abs(int value); public static float Abs(float value); public static double Abs(double value); public static long Abs(long value); public static decimal Abs(decimal value); This method takes the argument whose absolute value must be fond. Here is an example: using System; class Program { static int Main() { int number = 6844; Console.WriteLine("Original Value = {0}", number); Console.WriteLine("Absolute Value = {0}\n", Math.Abs(number)); return 0; } } This would produce: Original Value = 6844 Absolute Value = 6844 Press any key to continue . . .
Consider a floatingpoint number such as 12.155. This number is between integer 12 and integer 13: In the same way, consider a number such as 24.06. As this number is negative, it is between 24 and 25, with 24 being greater. In arithmetic, the ceiling of a number is the closest integer that is greater or higher than the number considered. In the first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.155. The ceiling of 24.06 is 24. To support the finding of a ceiling, the Math class is equipped with a method named Ceiling that is overloaded with two versions whose syntaxes are: public static double Ceiling(double a); public static decimal Ceiling(decimal d); This method takes as argument a floatingpoint number of variable whose ceiling needs to be found. Here is an example: using System; class Program { static int Main() { double value1 = 155.55; double value2 = 24.06; Console.WriteLine("The ceiling of {0} is {1}", value1, Math.Ceiling(value1)); Console.WriteLine("The ceiling of {0} is {1}\n", value2, Math.Ceiling(value2)); return 0; } } This would produce: The ceiling of 155.55 is 156 The ceiling of 24.06 is 24 Press any key to continue . . . Besides the Math class, the Double structure provides its own implementation of this method using the following syntax: public static decimal Ceiling(decimal d);
Consider two floating numbers such as 128.44 and 36.72. The number 128.44 is between 128 and 129 with 128 being the lower. The number 36.72 is between 37 and 36 with 37 being the lower. The lowest but closest integer value of a number is referred to as its floor. To assist you with finding the floor of a number, the Math class provides the Floor() method. It is overloaded in two versions whose syntaxes are: public static double Floor(double d); public static decimal Floor(decimal d); The floor() method takes the considered value as the argument and returns the integer that is less than or equal to Value. Here is an example: using System; class Program { static int Main() { double value1 = 1540.25; double value2 = 360.04; Console.WriteLine("The floor of {0} is {1}", value1, Math.Floor(value1)); Console.WriteLine("The floor of {0} is {1}\n", value2, Math.Floor(value2)); return 0; } } This would produce: The floor of 1540.25 is 1540 The floor of 360.04 is 361 Press any key to continue... Instead of using the Math class, the Double structure also has a method to find the floor of a decimal number. Its syntax is: public static decimal Ceiling(decimal d);
The power is the value of one number or expression raised to another number. This follows the formula: ReturnValue = x^{y} To support this operation, the Math class is equipped with a method named Pow whose syntax is public static double Pow(double x, double y); This method takes two arguments. The first argument, x, is used as the base number to be evaluated. The second argument, y, also called the exponent, will raise x to this value. Here is an example: using System; class Program { static int Main() { const double source = 25.38; const double exp = 3.12; double result = Math.Pow(source, exp); Console.WriteLine("Pow({0}, {1}) = {2}\n", source, exp, result); return 0; } } This would produce: Pow(25.38, 3.12) = 24099.8226934415 Press any key to continue . . .
You can calculate the exponential value of a number. To support this, the Math class provides the Exp() method. Its syntax is: public static double Exp (double d); Here is an example of calling this method: using System; class Program { static int Main() { Console.WriteLine("The exponential of {0} is {1}", 709.78222656, Math.Exp(709.78222656)); return 0; } } This would produce: The exponential of 709.78222656 is 1.79681906923757E+308 Press any key to continue . . . If the value of x is less than 708.395996093 (approximately), the result is reset to 0 and qualifies as underflow. If the value of the argument x is greater than 709.78222656 (approximately), the result qualifies as overflow.
To calculate the natural logarithm of a number, you can call the Math.Log() method. It is provides in two versions. The syntax of one is: public static double Log(double d); Here is an example: using System; class Program { static int Main() { double log = 12.48D; Console.WriteLine("Log of {0} is {1}", log, Math.Log(log)); return 0; } } This would produce: Log of 12.48 is 2.52412736294128 Press any key to continue . . .
The Math.Log10() method calculates the base 10 logarithm of a number. The syntax of this method is: public static double Log10(double d); The number to be evaluated is passed as the argument. The method returns the logarithm on base 10 using the formula: y = log_{10}x which is equivalent to x = 10^{y} Here is an example: using System; class Program { static int Main() { double log10 = 12.48D; Console.WriteLine("Log of {0} is {1}", log10, Math.Log10(log10)); return 0; } } This would produce: Log of 12.48 is 1.09621458534641 Press any key to continue . . .
The Math.Log() method provides another version whose syntax is: public static double Log(double a, double newBase); The variable whose logarithmic value will be calculated is passed as the first argument to the method. The second argument allows you to specify a base of your choice. The method uses the formula: Y = log_{NewBase}^{x} This is the same as x = NewBase^{y} Here is an example of calling this method: using System; class Program { static int Main() { double logN = 12.48D; Console.WriteLine("Log of {0} is {1}", logN, Math.Log(logN, 4)); return 0; } } This would produce: Log of 12.48 is 1.82077301454376 Press any key to continue . . .
You can calculate the square root of a decimal positive number. To support this, the Math class is equipped with a method named Sqrt whose syntax is: public static double Sqrt(double d); This method takes one argument as a positive floatingpoint number. After the calculation, the method returns the square root of x: using System; class Program { static int Main() { double sqrt = 8025.73D; Console.WriteLine("The square root of {0} is {1}", sqrt, Math.Sqrt(sqrt)); return 0; } } This would produce: The square root of 8025.73 is 89.5864387058666 Press any key to continue . . .
A circle is a group or series of distinct points drawn at an exact same distance from another point referred to as the center. The distance from the center C to one of these equidistant points is called the radius, R. The line that connects all of the points that are equidistant to the center is called the circumference of the circle. The diameter is the distance between two points of the circumference to the center; in other words, a diameter is double the radius. To manage the measurements and other related operations, the circumference is divided into 360 portions. Each of these portions is called a degree. The unit used to represent the degree is the degree, written as ˚. Therefore, a circle contains 360 degrees, that is 360˚. The measurement of two points A and D of the circumference could have 15 portions of the circumference. In this case, this measurement would be represents as 15˚. The distance between two equidistant points A and B is a round shape geometrically defined as an arc. An angle, ө, is the ratio of the distance between two points A and B of the circumference divided by the radius R. This can be written as: Therefore, an angle is the ratio of an arc over the radius. Because an angle is a ratio and not a physical measurement, which means an angle is not a dimension, it is independent of the size of a circle. Obviously this angle represents the number of portions included by the three points. A better unit used to measure an angle is the radian or rad. A cycle is a measurement of the rotation around the circle. Since the rotation is not necessarily complete, depending on the scenario, a measure is made based on the angle that was covered during the rotation. A cycle could cover part of the circle in which case the rotation would not have been completed. A cycle could also cover the whole 360˚ of the circle and continue there after. A cycle is equivalent to the radian divided by 2 * Pi.
The word п, also written as Pi, is a constant number used in various mathematical calculations. Its approximate value is 3.1415926535897932. The calculator of Windows represents it as 3.1415926535897932384626433832795. Borland had included its value in the math.h library as M_PI 3.14159265358979323846. A diameter is two times the radius. In geometry, it is written as 2R. In C++, it is written as 2 * R or R * 2 (because the multiplication is symmetric). The circumference of a circle is calculated by multiplying the diameter to Pi, which is 2Rп, or 2 * R * п or 2 * R * Pi. A radian is 2Rп/R radians or 2Rп/R rad, which is the same as 2п rad or 2 * Pi rad. To perform conversions between the degree and the radian, you can use the formula: 360˚ = 2п rad which is equivalent to 1 rad = 360˚ / 2п = 57.3˚.
Consider the following geometric figure:
Consider AB the length of A to B, also referred to as the hypotenuse. Also consider AC the length of A to C which is the side adjacent to point A. The cosine of the angle at point A is the ratio AC/AB. That is, the ratio of the adjacent length, AC, over the length of the hypotenuse, AB: The returned value, the ratio, is a doubleprecision number between 1 and 1. To calculate the cosine of an angle, the Math class provides the Cos() method. Its syntax is: public static double Cos(double d); Here is an example: using System; class Program { static int Main() { int number = 82; Console.WriteLine("The cosine of {0} is {1}", number, Math.Cos(number)); return 0; } } This would produce: The cosine of 82 is 0.949677697882543 Press any key to continue . . .
Consider AB the length of A to B, also called the hypotenuse to point A. Also consider CB the length of C to B, which is the opposite side to point A. The sine represents the ratio of CB/AB; that is, the ratio of the opposite side, CB over the hypotenuse AB. To calculate the sine of a value, you can call the Sin() method of the Math class. Its syntax is: public static double Sin(double a); Here is an example: using System; class Program { static int Main() { double number = 82.55; Console.WriteLine("The sine of {0} is {1}", number, Math.Sin(number)); return 0; } } This would produce: The sine of 82.55 is 0.763419622322519 Press any key to continue . . .
Consider AC the length of A to C. Also consider BC the length of B to C. The tangent is the result of BC/AC; that is, the ratio of BC over AC. To assist you with calculating the tangent of of a number, the Math class is equipped with a method named Tan whose syntax is: public static double Tan(double a); Here is an example: using System; class Program { static int Main() { uint number = 225; Console.WriteLine("The tangent of {0} is {1}", number, Math.Tan(number)); return 0; } } This would produce: The tangent of 225 is 2.53211499233434 Press any key to continue . . .
Consider BC the length of B to C. Also consider AC the length of A to C. The arc tangent is the ratio of BC/AC. To calculate the arc tangent of a value, you can use the Math.Atan() method. Its syntax is public static double Atan(double d); Here is an example: using System; class Program { static int Main() { short number = 225; Console.WriteLine("The arc tangent of {0} is {1}", number, Math.Atan(number)); return 0; } } This would produce: The arc tangent of 225 is 1.56635191161394 Press any key to continue . . .



Previous  Copyright © 20082015, FunctionX, Inc.  Next 
