Skip to main content

4.2 - Working with Math

The .NET Framework provides robust support for mathematical operations through the System.Math class. This static class contains methods and constants for performing common mathematical functions, making it easier to implement complex calculations in your C# applications.

4.2.1 - Basic Math Operations

C# supports all the standard arithmetic operators for performing basic mathematical operations.

4.2.1.1 - Arithmetic Operators

The basic arithmetic operators in C# are:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%) - returns the remainder of a division operation

Example:

using System;

class Program
{
static void Main()
{
int a = 10;
int b = 3;

// Basic arithmetic operations
Console.WriteLine($"Addition: {a} + {b} = {a + b}");
Console.WriteLine($"Subtraction: {a} - {b} = {a - b}");
Console.WriteLine($"Multiplication: {a} * {b} = {a * b}");
Console.WriteLine($"Division: {a} / {b} = {a / b}"); // Integer division
Console.WriteLine($"Modulus: {a} % {b} = {a % b}"); // Remainder

// For floating-point division
double c = 10.0;
double d = 3.0;
Console.WriteLine($"Floating-point division: {c} / {d} = {c / d}");
}
}

Output:

Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3
Modulus: 10 % 3 = 1
Floating-point division: 10 / 3 = 3.3333333333333335

4.2.1.2 - Math Class Basic Methods

The Math class provides several methods for common mathematical operations:

  • Math.Abs(): Returns the absolute value of a number
  • Math.Max(): Returns the larger of two numbers
  • Math.Min(): Returns the smaller of two numbers
  • Math.Pow(): Returns a specified number raised to a specified power
  • Math.Sqrt(): Returns the square root of a number
  • Math.Round(): Rounds a value to the nearest integer or to a specified number of decimal places
  • Math.Floor(): Returns the largest integer less than or equal to a number
  • Math.Ceiling(): Returns the smallest integer greater than or equal to a number
  • Math.Truncate(): Returns the integral part of a number by removing any fractional digits

Example:

using System;

class Program
{
static void Main()
{
// Absolute value
Console.WriteLine($"Absolute value of -5: {Math.Abs(-5)}");

// Maximum and minimum
Console.WriteLine($"Maximum of 10 and 20: {Math.Max(10, 20)}");
Console.WriteLine($"Minimum of 10 and 20: {Math.Min(10, 20)}");

// Power and square root
Console.WriteLine($"2 raised to the power of 3: {Math.Pow(2, 3)}");
Console.WriteLine($"Square root of 16: {Math.Sqrt(16)}");

// Rounding
double value = 3.75;
Console.WriteLine($"Round {value}: {Math.Round(value)}");
Console.WriteLine($"Round {value} to 1 decimal place: {Math.Round(value, 1)}");

// Floor, ceiling, and truncate
Console.WriteLine($"Floor of {value}: {Math.Floor(value)}");
Console.WriteLine($"Ceiling of {value}: {Math.Ceiling(value)}");
Console.WriteLine($"Truncate {value}: {Math.Truncate(value)}");
}
}

Output:

Absolute value of -5: 5
Maximum of 10 and 20: 20
Minimum of 10 and 20: 10
2 raised to the power of 3: 8
Square root of 16: 4
Round 3.75: 4
Round 3.75 to 1 decimal place: 3.8
Floor of 3.75: 3
Ceiling of 3.75: 4
Truncate 3.75: 3

4.2.2 - Advanced Math Functions

The Math class also provides methods for more advanced mathematical operations, such as trigonometric, logarithmic, and exponential functions.

4.2.2.1 - Trigonometric Functions

The Math class includes the following trigonometric functions:

  • Math.Sin(): Returns the sine of an angle in radians
  • Math.Cos(): Returns the cosine of an angle in radians
  • Math.Tan(): Returns the tangent of an angle in radians
  • Math.Asin(): Returns the angle whose sine is the specified number
  • Math.Acos(): Returns the angle whose cosine is the specified number
  • Math.Atan(): Returns the angle whose tangent is the specified number
  • Math.Atan2(): Returns the angle whose tangent is the quotient of two specified numbers

Example:

using System;

class Program
{
static void Main()
{
// Convert degrees to radians
double DegreesToRadians(double degrees)
{
return degrees * Math.PI / 180.0;
}

// Convert radians to degrees
double RadiansToDegrees(double radians)
{
return radians * 180.0 / Math.PI;
}

// Trigonometric functions
double angle = 45.0; // in degrees
double radians = DegreesToRadians(angle);

Console.WriteLine($"Angle: {angle} degrees = {radians:F4} radians");
Console.WriteLine($"Sin({angle}°) = {Math.Sin(radians):F4}");
Console.WriteLine($"Cos({angle}°) = {Math.Cos(radians):F4}");
Console.WriteLine($"Tan({angle}°) = {Math.Tan(radians):F4}");

// Inverse trigonometric functions
double value = 0.5;
Console.WriteLine($"Asin({value}) = {RadiansToDegrees(Math.Asin(value)):F4}°");
Console.WriteLine($"Acos({value}) = {RadiansToDegrees(Math.Acos(value)):F4}°");
Console.WriteLine($"Atan({value}) = {RadiansToDegrees(Math.Atan(value)):F4}°");

// Atan2 example (useful for determining angle from coordinates)
double y = 1.0;
double x = 1.0;
double angleInRadians = Math.Atan2(y, x);
Console.WriteLine($"Atan2({y}, {x}) = {RadiansToDegrees(angleInRadians):F4}°");
}
}

4.2.2.2 - Logarithmic and Exponential Functions

The Math class provides the following logarithmic and exponential functions:

  • Math.Log(): Returns the natural logarithm (base e) of a specified number
  • Math.Log10(): Returns the base 10 logarithm of a specified number
  • Math.Log2(): Returns the base 2 logarithm of a specified number (available in .NET Core 3.0 and later)
  • Math.Exp(): Returns e raised to the specified power

Example:

using System;

class Program
{
static void Main()
{
// Logarithmic functions
double value = 100.0;

Console.WriteLine($"Natural logarithm (base e) of {value}: {Math.Log(value):F4}");
Console.WriteLine($"Base 10 logarithm of {value}: {Math.Log10(value):F4}");

// In .NET Core 3.0 and later
// Console.WriteLine($"Base 2 logarithm of {value}: {Math.Log2(value):F4}");

// Custom base logarithm
double customBase = 5.0;
double customBaseLog = Math.Log(value) / Math.Log(customBase);
Console.WriteLine($"Base {customBase} logarithm of {value}: {customBaseLog:F4}");

// Exponential function
double power = 2.0;
Console.WriteLine($"e^{power} = {Math.Exp(power):F4}");

// Verify logarithm and exponential are inverse functions
double x = 5.0;
Console.WriteLine($"Log(Exp({x})) = {Math.Log(Math.Exp(x)):F4}");
Console.WriteLine($"Exp(Log({x})) = {Math.Exp(Math.Log(x)):F4}");
}
}

4.2.2.3 - Hyperbolic Functions

The Math class includes the following hyperbolic functions:

  • Math.Sinh(): Returns the hyperbolic sine of an angle
  • Math.Cosh(): Returns the hyperbolic cosine of an angle
  • Math.Tanh(): Returns the hyperbolic tangent of an angle

Example:

using System;

class Program
{
static void Main()
{
// Hyperbolic functions
double x = 1.0;

Console.WriteLine($"Sinh({x}) = {Math.Sinh(x):F4}");
Console.WriteLine($"Cosh({x}) = {Math.Cosh(x):F4}");
Console.WriteLine($"Tanh({x}) = {Math.Tanh(x):F4}");

// Verify the fundamental hyperbolic identity: cosh²(x) - sinh²(x) = 1
double identity = Math.Pow(Math.Cosh(x), 2) - Math.Pow(Math.Sinh(x), 2);
Console.WriteLine($"cosh²({x}) - sinh²({x}) = {identity:F10}");
}
}

4.2.3 - Random Number Generation

C# provides the Random class for generating random numbers, which is useful for simulations, games, and statistical applications.

4.2.3.1 - Basic Random Number Generation

The Random class provides methods for generating random integers and doubles:

  • Random.Next(): Returns a non-negative random integer
  • Random.Next(int maxValue): Returns a non-negative random integer less than the specified maximum
  • Random.Next(int minValue, int maxValue): Returns a random integer within a specified range
  • Random.NextDouble(): Returns a random floating-point number between 0.0 and 1.0

Example:

using System;

class Program
{
static void Main()
{
// Create a new Random object
Random random = new Random();

// Generate random integers
int randomInt1 = random.Next();
int randomInt2 = random.Next(100); // 0 to 99
int randomInt3 = random.Next(50, 101); // 50 to 100

Console.WriteLine($"Random integer: {randomInt1}");
Console.WriteLine($"Random integer (0-99): {randomInt2}");
Console.WriteLine($"Random integer (50-100): {randomInt3}");

// Generate random doubles
double randomDouble1 = random.NextDouble();
double randomDouble2 = random.NextDouble() * 100; // 0.0 to 100.0
double randomDouble3 = 50 + random.NextDouble() * 50; // 50.0 to 100.0

Console.WriteLine($"Random double (0-1): {randomDouble1:F4}");
Console.WriteLine($"Random double (0-100): {randomDouble2:F4}");
Console.WriteLine($"Random double (50-100): {randomDouble3:F4}");
}
}

4.2.3.2 - Generating Random Bytes

The Random class also provides a method for filling an array with random bytes:

  • Random.NextBytes(byte[] buffer): Fills the elements of a specified array of bytes with random numbers

Example:

using System;

class Program
{
static void Main()
{
Random random = new Random();

// Generate random bytes
byte[] buffer = new byte[10];
random.NextBytes(buffer);

Console.WriteLine("Random bytes:");
foreach (byte b in buffer)
{
Console.Write($"{b} ");
}
Console.WriteLine();
}
}

4.2.3.3 - Seeding the Random Number Generator

The Random class constructor can take a seed value, which initializes the random number generator. Using the same seed will produce the same sequence of random numbers.

Example:

using System;

class Program
{
static void Main()
{
// Create two Random objects with the same seed
int seed = 42;
Random random1 = new Random(seed);
Random random2 = new Random(seed);

Console.WriteLine("Random numbers with the same seed:");
for (int i = 0; i < 5; i++)
{
int value1 = random1.Next(100);
int value2 = random2.Next(100);
Console.WriteLine($"random1: {value1}, random2: {value2}");
}

// Create two Random objects with different seeds
Random random3 = new Random(123);
Random random4 = new Random(456);

Console.WriteLine("\nRandom numbers with different seeds:");
for (int i = 0; i < 5; i++)
{
int value3 = random3.Next(100);
int value4 = random4.Next(100);
Console.WriteLine($"random3: {value3}, random4: {value4}");
}
}
}

4.2.3.4 - Generating Random Values for Different Types

You can use the Random class to generate random values for different types:

Example:

using System;

class Program
{
static void Main()
{
Random random = new Random();

// Generate a random boolean
bool randomBool = random.Next(2) == 1;
Console.WriteLine($"Random boolean: {randomBool}");

// Generate a random character
char randomChar = (char)random.Next(65, 91); // ASCII values for uppercase letters
Console.WriteLine($"Random uppercase letter: {randomChar}");

// Generate a random date within a range
DateTime start = new DateTime(2000, 1, 1);
int range = (DateTime.Today - start).Days;
DateTime randomDate = start.AddDays(random.Next(range));
Console.WriteLine($"Random date: {randomDate:d}");

// Generate a random item from an array
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
string randomFruit = fruits[random.Next(fruits.Length)];
Console.WriteLine($"Random fruit: {randomFruit}");

// Generate a random decimal
decimal randomDecimal = (decimal)(random.Next(10000) / 100.0);
Console.WriteLine($"Random decimal: {randomDecimal:C}");
}
}

4.2.4 - Mathematical Constants

The Math class provides several mathematical constants that are commonly used in calculations.

4.2.4.1 - Built-in Constants

The Math class includes the following constants:

  • Math.PI: Represents the ratio of the circumference of a circle to its diameter (approximately 3.14159265358979)
  • Math.E: Represents the natural logarithmic base (approximately 2.71828182845905)

Example:

using System;

class Program
{
static void Main()
{
// Using Math.PI
Console.WriteLine($"Value of π (Pi): {Math.PI}");

// Calculate the circumference of a circle
double radius = 5.0;
double circumference = 2 * Math.PI * radius;
Console.WriteLine($"Circumference of a circle with radius {radius}: {circumference:F2}");

// Calculate the area of a circle
double area = Math.PI * Math.Pow(radius, 2);
Console.WriteLine($"Area of a circle with radius {radius}: {area:F2}");

// Using Math.E
Console.WriteLine($"Value of e (Euler's number): {Math.E}");

// Calculate compound interest using e
double principal = 1000.0;
double rate = 0.05; // 5%
double time = 10.0; // 10 years
double continuousCompound = principal * Math.Exp(rate * time);
Console.WriteLine($"$1000 with 5% continuous compound interest after 10 years: {continuousCompound:C2}");
}
}

4.2.4.2 - Defining Custom Constants

You can define your own mathematical constants as needed:

Example:

using System;

class MathConstants
{
// Defining custom mathematical constants
public const double GoldenRatio = 1.61803398874989;
public const double SqrtTwo = 1.41421356237309;
public const double SqrtThree = 1.73205080756888;
public const double NaturalLog10 = 2.30258509299405;
}

class Program
{
static void Main()
{
// Using custom constants
Console.WriteLine($"Golden Ratio (φ): {MathConstants.GoldenRatio}");
Console.WriteLine($"Square root of 2: {MathConstants.SqrtTwo}");
Console.WriteLine($"Square root of 3: {MathConstants.SqrtThree}");
Console.WriteLine($"Natural logarithm of 10: {MathConstants.NaturalLog10}");

// Verify the values
Console.WriteLine($"Math.Sqrt(2) = {Math.Sqrt(2)}");
Console.WriteLine($"Math.Sqrt(3) = {Math.Sqrt(3)}");
Console.WriteLine($"Math.Log(10) = {Math.Log(10)}");
}
}

4.2.4.3 - Practical Applications of Mathematical Constants

Here are some practical applications of mathematical constants:

Example:

using System;

class Program
{
static void Main()
{
// Calculate the volume of a sphere
double radius = 3.0;
double volume = (4.0 / 3.0) * Math.PI * Math.Pow(radius, 3);
Console.WriteLine($"Volume of a sphere with radius {radius}: {volume:F2} cubic units");

// Calculate the normal distribution probability density function
double mean = 0.0;
double stdDev = 1.0;
double x = 0.5;
double normalPdf = (1.0 / (stdDev * Math.Sqrt(2 * Math.PI))) *
Math.Exp(-0.5 * Math.Pow((x - mean) / stdDev, 2));
Console.WriteLine($"Normal PDF at x={x}, mean={mean}, stdDev={stdDev}: {normalPdf:F6}");

// Calculate the half-life decay
double initialAmount = 100.0;
double halfLife = 5.0; // in years
double decayConstant = Math.Log(2) / halfLife;
double time = 10.0; // in years
double remainingAmount = initialAmount * Math.Exp(-decayConstant * time);
Console.WriteLine($"Amount remaining after {time} years with half-life of {halfLife} years: {remainingAmount:F2}");
}
}

The Math class and related functionality in C# provide a comprehensive set of tools for performing mathematical operations, from basic arithmetic to advanced functions. By leveraging these capabilities, you can implement complex mathematical algorithms and calculations in your applications with ease and precision.