Introduction to the Built-In Math Class

Introduction

To help you perform some basic algebraic and geometric operations in your application, the .NET Framework provides a static class named Math. Besides the Math class, 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. Practical Learning: Introducing Math Functions

• Start Microsoft Visual Studio and create a new Console App named CompoundInterest1 that uses the .NET 7.0 (Standard Term Support)

The Sign of a Number

When initializing a numeric variable using a constant, you decide whether it is negative, 0 or positive. This is referred to as its sign. To help you determine the sign of a variable or of a number, the Math static class provides a method named Sign(). It is overloaded in various versions for each type. When calling this method, pass the value or the variable you want to consider, as argument. The method returns:

• -1 if the argument is negative
• 0 if the argument is 0
• 1 if the argument is positive

The Integral Side of a Floating-Point Number

We already know that a decimal number consists of an integral side and a precision side; both are separated by the decimal symbol which, in US English, is the period. To let you get the integral side of a decimal value, the Math static class provides a method named Truncate. It 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 that holds a numeric value. The method returns the int side of the value.

The Minimum of Two Values

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 function member named Min. This function is overloaded in various versions with each version adapted to each integral or decimal type. Here is an example:

```using static System.Console;

double number = 508_206.82_741;
double value  = 294_835.69_525;

WriteLine("Number:  {0}", number);
WriteLine("Number:  {0}", value);
WriteLine("----------------------");
WriteLine("Minimum: {0}", Math.Min(number, value));
WriteLine("======================");```

This would produce:

```Number:  508206.82741
Number:  294835.69525
----------------------
Minimum: 294835.69525
======================```

The Maximum of Two Values

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, the Math class is equipped with a function member named Max. It is overloaded in various versions with one for each type of numeric data. Here is an example:

```using static System.Math;
using static System.Console;

double number = 508_206.82_741;
double value  = 294_835.69_525;

WriteLine("Number:  {0}", number);
WriteLine("Number:  {0}", value);
WriteLine("----------------------");
WriteLine("Minimum: {0}", Min(number, value));
WriteLine("Maximum: {0}", Max(number, value));
WriteLine("======================");```

This would produce:

```Number:  508206.82741
Number:  294835.69525
----------------------
Minimum: 294835.69525
Maximum: 508206.82741
======================```

Value Conversions

Implicit Conversions

If you have code with mixed types of variables, you may need to convert a value from one type to another. Implicit conversion is the ability to convert a value of one type into a value of another type. This is possible when the amount of memory that one type is using is lower than the amount necessary for another type. For example, a value of an integer can be directly converted into a double type. Here is an example:

```int iNumber = 2445;

double dNumber = iNumber;```

In the same way, as saw in our introduction to the double type, you can assign an integral value to a variable of type double. Here is an example:

`double number = 927084;`

This characteristic is referred to as implicit conversion.

Explicit Conversions

Because of memory requirements, the direct reverse of implicit conversion is not possible. Since the memory reserved for an int variable is smaller than that of a double, you cannot assign a value of type double to a variable of type int. As a result, the following code produces an error:

`int hourlySalary = 24.75;`

In the same way, you cannot assign a variable of type double to a variable of type int. This means that the following code produces an error:

```double nbr = 9270.84;

int number = nbr;```

Value Casting

Value casting consists of converting a value of one type into a value of another type. Value casting 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:

```double number = 9270.84;

int nbr = (int)number;```

When performing explicit conversion, that is, when casting, you should pay close attention to the value that is being cast. If a value cannot fit in the memory of the other, you may get an unpredictable result.

Arithmetic

Absolute Values

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. To let you get the absolute value of a number, the Math static class is equipped with a method named Abs, which is overloaded in various versions. The syntax for the int and the double types are:

```public static int Abs(int value);
public static double Abs(double value);```

This method takes the argument whose absolute value must be found.

The Ceiling of a Number

Consider a floating-point 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 static class is equipped with a method named Ceiling that is overloaded with two versions. The syntax for a double value is:

`public static double Ceiling(double a);`

This method takes as argument a number or variable whose ceiling needs to be found. Here is an example:

```using static System.Console;

double value1 = 155.55;
double value2 = -24.06;

double nbr1 = Math.Ceiling(value1));
double nbr2 = Math.Ceiling(value2));

WriteLine("Number:  {0}", value1);
WriteLine("Ceiling: {0}", nbr1);
WriteLine("----------------------");
WriteLine("Number:  {0}", value2);
WriteLine("Ceiling: {0}", nbr2);
WriteLine("======================");```

This would produce:

```Number:  155.55
Ceiling: 156
----------------------
Minimum: -24.06
Maximum: -24
======================```

The Floor of a Number

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 static class provides the Floor() method. It is overloaded with two versions. The syntax for a double is:

`public static double Floor(double d);`

The Math.Floor() method takes the considered value as the argument and returns the integer that is less than or equal to the argument. Here is an example:

```using static System.Console;

double value1 = 1540.25;
double value2 = -360.04;

double nbr1 = Math.Floor(value1);
double nbr2 = Math.Floor(value2);

WriteLine("Number: {0}", value1);
WriteLine("Floor:  {0}", nbr1);
WriteLine("----------------------");
WriteLine("Number: {0}", value2);
WriteLine("Floor:  {0}", nbr2);
WriteLine("======================");```

This would produce:

```Number: 1540.25
Floor:  1540
----------------------
Number: -360.04
Floor:  -361
======================```

The Power of a Number

The power is the value of one number or expression raised to another number. This follows the formula:

`value = xy`

To support this operation, the Math static class is equipped with a method named Pow. Its 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. Practical Learning: Getting the Power of a Number

1. Change the document as follows:
```using static System.Console;

double frequency = 12.00;

WriteLine("Compound Interest");
WriteLine("======================================================");
WriteLine("Provide the values to calculate a compound interest");
WriteLine("------------------------------------------------------");

double periods      = 0.00;
double principal    = 0.00;
double interestRate = 0.00;

try {
Write("Principal:        ");
}
catch(FormatException fe){
WriteLine("The value for the principal is not valid. Please report the error as follows: " + fe.Message);
}

try {
Write("Interest Rate:    ");
}
catch(FormatException fe){
WriteLine("The value for the interest rate is not valid. Please report the error as follows: " + fe.Message);
}

try {
Write("Periods:          ");
}
catch(FormatException fe){
WriteLine("The value for the period is not valid. Please report the error as follows: " + fe.Message);
}

double per = periods / 100;

double futureValue = principal * Math.Pow((1.00 + (interestRate / frequency)), frequency * per);
double interestEarned = futureValue - principal;

WriteLine("======================================================");
WriteLine("Compound Interest");
WriteLine("======================================================");
WriteLine("Principal:        {0:f}", principal);
WriteLine("Interest Rate:    {0:f}%", interestRate);
WriteLine("Periods:          {0} years", periods);
WriteLine("------------------------------------------------------");
WriteLine("Future Value:     {0:f}", futureValue);
WriteLine("Interest Earned:  {0:f}", interestEarned);
WriteLine("======================================================");```
3. When requested, type the Principal as 5284.65 and press Enter
4. Type the Interest Rate 12.35 and press Enter
5. Type the Periods as 5 and press Enter:
```Compound Interest
======================================================
Provide the values to calculate a compound interest
------------------------------------------------------
Principal:        5284.65
Interest Rate:    12.35
Periods:          5
======================================================
Compound Interest
======================================================
Principal:        5284.65
Interest Rate:    12.35%
Periods:          5 years
------------------------------------------------------
Future Value:     8079.92
Interest Earned:  2795.27
======================================================

Press any key to close this window . . .```
7. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
8. Make sure Console App is selected. Click Next
9. Change the project Name to Geometry08 and change or accept the project Location
10. Click Next
11. Make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support). Click Create
12. To create a new folder, in the Solution Explorer, right-click Geometry08 -> Add -> New Folder
13. Type Models as the name of the folder
14. In the Solution Explorer, right-click Models -> Add -> Class...
15. Change the file Name to EquilateralTriangle
16. Press Enter

The Exponential

To let you calculate the exponential value of a number, the Math static class provides the Exp() method. Its syntax is:

`public static double Exp(double d);`

If the value of the argument 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.

Here is an example of calling this method:

```using static System.Console;

Write("The exponential of ");
Write(709.78222656);
Write(" is ");
WriteLine(Math.Exp(709.78222656));```

This would produce:

```The exponential of 709.78222656 is 1.79681906923757E+308
Press any key to close this window . . .```

The Natural Logarithm

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;
using static System.Console;

double log = 12.48;

Write("Log of ");
Write(log);
Write(" is ");
WriteLine(Math.Log(log));```

This would produce:

```Log of 12.48 is 2.52412736294128
Press any key to close this window . . .```

The Base 10 Logarithm

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 = log10x`

which is equivalent to

`x = 10y`

Here is an example:

```using System;
using static System.Console;

double log10 = 12.48;

Write("Log of ");
Write(log10);
Write(" is ");
WriteLine(Math.Log10(log10));```

This would produce:

```Log of 12.48 is 1.09621458534641
Press any key to close this window . . .```

The Logarithm of Any Base

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 = logNewBasex`

This is the same as

`x = NewBasey`

Here is an example of calling this method:

```using static System.Console;

double logN = 12.48;

Write("Log of ");
Write(logN);
Write(" is ");
WriteLine(Math.Log(logN, 4));```

This would produce:

```Log of 12.48 is 1.82077301454376
Press any key to close this window . . .```

The Square Root

You can calculate the square root of a decimal positive number. To support this, the Math static 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 floating-point number. After the calculation, the method returns the square root of x:

```using System;

double sqrt = 8025.73;

double number = Math.Sqrt(sqrt));``` Practical Learning: Finding the Square Root of a Number

1. In the empty document, create a class as follows:
```using static System.Math;

namespace Geometry08.Models;
{
internal class EquilateralTriangle
{
private double s;
const double NumberOfSides = 3;

public EquilateralTriangle(double side) => s = side;

public double Side
{
get { return s;  }
set { s = value; }
}

public double Perimeter    => s * NumberOfSides;
public double Height       => s * Sqrt(3) / 2;
public double Area         => s * s * Sqrt(3) / 4;
public double Inradius     => s * Sqrt(3) / 6;
public double Circumradius => s / Sqrt(3);
}
}```
2. In the Solution Explorer, right-click Program.cs -> Rename
3. Type Geometry (to get Geometry.cs) and press Enter
4. Read the content of the message box and press Enter twice
5. Change the document as follows:
```using static System.Console;

using Geometry08.Models;

WriteLine("====================================================");
WriteLine("Enter the value to process the equilateral triangle");

double side = 0.00;

try
{
Write("Side:       ");
}
catch(FormatException fe){
WriteLine("The value for the side of the triangle is not valid. Please report the error as follows: " + fe.Message);
}

EquilateralTriangle et = new EquilateralTriangle(side);

WriteLine("====================================================");
WriteLine("Geometry - Equilateral Triangle");
WriteLine("====================================================");
WriteLine("Side:        {0}", et.Side);
WriteLine("----------------------------------------------------");
WriteLine("Height:      {0}", et.Height);
WriteLine("Perimeter:   {0}", et.Perimeter);
WriteLine("Area:        {0}", et.Area);
WriteLine("====================================================");```
6. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging
7. When requested, type the Side as 309.66 and press Enter:
```====================================================
Enter the value to process the equilateral triangle
Side:       309.66
====================================================
Geometry - Equilateral Triangle
====================================================
Side:        309.66
----------------------------------------------------
Height:      268.1734265358893
Perimeter:   928.98
Area:        41521.29163055174
Bottom Area: 178.78228435725953
====================================================

Press any key to close this window . . .```
9. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
10. Make sure Console App are selected.
Click Next
11. Replace the suggested name of the project with Geometry09
12. Click Next
13. Make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support).
Press Enter
14. To create a new folder, in the Solution Explorer, right-click Geometry09 -> Add -> New Folder
15. Type Models as the name of the folder
16. In the Solution Explorer, right-click Models -> Add -> Class...
17. Change the file name to Square
19. Change the document as follows:
```using static System.Math;

namespace Geometry09.Models
{
internal class Square
{
public double Side { get; set; }

public Square(double side)
{
Side = side;
}

public double Perimeter
{
get
{
return Side * 4.00;
}
}

public virtual double Area
{
get
{
return Side * Side;
}
}

{
return Side / 2.00;
}

{
return Sqrt(2.00) * Side / 2.00;
}
}
}```
20. In the Solution Explorer, right-click Program.cs and click Rename
21. type Geometry (to get Geometry.cs) and press Enter
22. Read the text in the message box and click Yes
23. Click the Geometry.cs tab to access the file and change the document as follows:
```using static System.Console;
using Geometry09.Models;

WriteLine("====================================================");
WriteLine("Enter the value to process the equilateral triangle");

double side = 0.00;

try
{
Write("Side:                 ");
}
catch(FormatException fe){
WriteLine("The value for the side of the square is not valid. Please report the error as follows: " + fe.Message);
}

Square sqr = new Square(side);

WriteLine("====================================================");
WriteLine("Geometry - Equilateral Triangle");
WriteLine("====================================================");
WriteLine("Side:                 {0}", sqr.Side);
WriteLine("----------------------------------------------------");
WriteLine("Perimeter:            {0}", sqr.Perimeter);
WriteLine("Area:                 {0}", sqr.Area);
WriteLine("====================================================");```
24. To execute the application to test the webpage, press Ctrl + F5
25. In the Side text box, type a number such as 429.63 and press Enter:
```====================================================
Enter the value to process the equilateral triangle
Side:                 429.63
====================================================
Geometry - Equilateral Triangle
====================================================
Side:                 429.63
----------------------------------------------------
Perimeter:            1718.52
Area:                 184581.9369
====================================================

Press any key to close this window . . .```
27. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
28. Make sure Console App is selected. Click Next
29. Replace the name of the project with Geometry10
30. Click Next
31. Make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support). Press Enter
32. To create a new folder, in the Solution Explorer, right-click Geometry10 -> Add -> New Folder
33. Type Models as the name of the folder
34. In the Solution Explorer, right-click Models -> Add -> Class...
35. Change the name of the file to Trapezoid
37. Change the class as follows:
```using static System.Math;

namespace Geometry09.Models
{
internal class Trapezoid
{
public double ShortSide { get; set; }
public double LongSide  { get; set; }
public double Edge      { get; set; }

public Trapezoid(double sSide, double lSide, double edge)
{
ShortSide = sSide;
LongSide  = lSide;
Edge      = edge;
}

public double Perimeter => LongSide + Edge + ShortSide + Edge;

// http://mathworld.wolfram.com/IsoscelesTrapezoid.html
public double Height
{
get
{
return Sqrt((Edge * Edge) - (Pow(LongSide - ShortSide, 2.00) / 4.00));
}
}

virtual public double CalculateArea()
{
return (LongSide + ShortSide) * Height / 2.00;
}
}
}```
38. Click the Program.cs tab and change the document as follows:
```using static System.Console;
using Geometry09.Models;

void Show(Trapezoid brick)
{
WriteLine("====================================================");
WriteLine("Geometry - Trapezoid");
WriteLine("====================================================");
WriteLine("Short Side:   {0}", brick.ShortSide);
WriteLine("Long Side:    {0}", brick.LongSide);
WriteLine("Edge:         {0}", brick.Edge);
WriteLine("----------------------------------------------------");
WriteLine("Perimeter:    {0}", brick.Perimeter);
WriteLine("Height:       {0}", brick.Height);
WriteLine("Area:         {0}", brick.CalculateArea());
WriteLine("====================================================");
}

Trapezoid CreateShape()
{
Trapezoid trap = new Trapezoid(sSide: 0.00, lSide: 0.00, edge: 0.00);

WriteLine("====================================================");
WriteLine("Enter the value to process the trapezoid");
WriteLine("----------------------------------------------------");

double border    = 0.00;
double longSide  = 0.00;
double shortSide = 0.00;

try
{
Write("Short Side:   ");
}
catch(FormatException fe){
WriteLine("The value for the short side of the trapezoid is not valid. Please report the error as follows: " + fe.Message);
}

try
{
Write("Long Side:    ");
}
catch(FormatException fe){
WriteLine("The value for the long side of the trapezoid is not valid. Please report the error as follows: " + fe.Message);
}

try
{
Write("Border:       ");
}
catch(FormatException fe){
WriteLine("The value for the long side of the trapezoid is not valid. Please report the error as follows: " + fe.Message);
}

trap = new Trapezoid(sSide: shortSide, lSide: longSide, border);

return trap;
}

Trapezoid shape = CreateShape();

Show(shape);```
40. When requested, type the Short Side as 137.96 and press Enter
41. For the Long Side, type as 209.73 and press Enter
42. For the Edge, type 87.59 and press Enter:
```====================================================
Enter the value to process the trapezoid
----------------------------------------------------
Short Side:   137.96
Long Side:    209.73
Border:       87.59
====================================================
Geometry - Trapezoid
====================================================
Short Side:   137.96
Long Side:    209.73
Edge:         87.59
----------------------------------------------------
Perimeter:    522.87
Height:       79.90165752348321
Area:         13890.503652169939
====================================================

Press any key to close this window . . .```
44. In the Solution Explorer, right-click Models -> Add -> Class...
45. Set the name of the class as TrapezoidalPrism
47. Fill the class as follows:
```namespace Geometry09.Models
{
internal class TrapezoidalPrism : Trapezoid
{
public double Length { get; set; }

public TrapezoidalPrism(double sSide, double lSide, double side, double len)
: base(sSide, lSide, side)
{
Length = len;
}

public double BaseArea => base.CalculateArea();

override public double CalculateArea()
{
double shortArea = ShortSide * Length;
double longArea = LongSide * Length;
double sideArea = Edge * Length;
return (BaseArea * 2.00) + shortArea + longArea + (sideArea * 2.00);
}

public double Volume => BaseArea * Length;
}
}```
48. Click the Geometry.cs tab to access the file
49. Change the document as follows:
```using static System.Console;
using Geometry09.Models;

void Show(TrapezoidalPrism brick)
{
WriteLine("====================================================");
WriteLine("Geometry - Trapezoidal Prism");
WriteLine("====================================================");
WriteLine("Short Side:   {0}", brick.ShortSide);
WriteLine("Long Side:    {0}", brick.LongSide);
WriteLine("Edge:         {0}", brick.Edge);
WriteLine("Length:       {0}", brick.Length);
WriteLine("----------------------------------------------------");
WriteLine("Perimeter:    {0}", brick.Perimeter);
WriteLine("Height:       {0}", brick.Height);
WriteLine("Base Area:    {0}", brick.BaseArea);
WriteLine("Total Area:   {0}", brick.CalculateArea());
WriteLine("Volume:       {0}", brick.Volume);
WriteLine("====================================================");
}

TrapezoidalPrism CreateShape()
{
WriteLine("====================================================");
WriteLine("Enter the value to process the trapezoidal prism");
WriteLine("----------------------------------------------------");

double edge      = 0.00;
double length    = 0.00;
double longSide  = 0.00;
double shortSide = 0.00;

try
{
Write("Short Side:   ");
}
catch(FormatException fe){
WriteLine("The value for the short side of the trapezoid is not valid. Please report the error as follows: " + fe.Message);
}

try
{
Write("Long Side:    ");
}
catch(FormatException fe){
WriteLine("The value for the long side of the trapezoid is not valid. Please report the error as follows: " + fe.Message);
}

try
{
Write("Edge:       ");
}
catch(FormatException fe){
WriteLine("The value for the edge of the trapezoidal prism is not valid. Please report the error as follows: " + fe.Message);
}

try
{
Write("Length:       ");
}
catch(FormatException fe){
WriteLine("The value for the length of the trapezoidal prism is not valid. Please report the error as follows: " + fe.Message);
}

return new TrapezoidalPrism(shortSide, longSide, edge, length);
}

TrapezoidalPrism shape = CreateShape();

Show(shape);```
51. For the Short Side, type 229.47 and press Enter
52. For the Long Side, type 167.66 and press Enter
53. For the Edge, type 98.59 and press Enter
54. For the Length, type 214.85 and press Enter:
```====================================================
Enter the value to process the trapezoidal prism
----------------------------------------------------
Short Side:   229.47
Long Side:    167.66
Edge:         98.59
Length:       214.85
====================================================
Geometry - Trapezoidal Prism
====================================================
Short Side:   229.47
Long Side:    167.66
Edge:         98.59
Length:       214.85
----------------------------------------------------
Perimeter:    594.3100000000001
Height:       93.62087948208989
Base Area:    18589.82993436118
Total Area:   164867.16336872234
Volume:       3994024.9613974993
====================================================

Press any key to close this window . . .```