C# Math

Performing mathematical operations in C#

🔢 What is the Math Class?

The Math class in C# provides methods for performing mathematical operations like finding maximum values, calculating square roots, rounding numbers, and working with trigonometric functions for advanced calculations.


// Using Math class methods
int max = Math.Max(10, 20);
int min = Math.Min(10, 20);
double sqrt = Math.Sqrt(64);

Console.WriteLine(max);  // Output: 20
Console.WriteLine(min);  // Output: 10
Console.WriteLine(sqrt); // Output: 8
                                    

Output:

20

10

8

Common Math Methods

📊

Max & Min

Find largest or smallest value

int max = Math.Max(5, 10);
int min = Math.Min(5, 10);

Square Root

Calculate square root of a number

double result = Math.Sqrt(64);
// result = 8
🔄

Rounding

Round numbers up, down, or nearest

double rounded = Math.Round(4.7);
// rounded = 5
📐

Power

Raise number to a power

double result = Math.Pow(2, 3);
// result = 8

🔹 Max and Min Methods

The Math.Max() and Math.Min() methods compare two numbers and return the larger or smaller value, respectively. For example: Math.Max(10, 20) returns 20. These methods are essential for finding extremes in datasets, validating ranges, or implementing business rules like pricing limits. They support various numeric types (int, double, etc.) and are commonly used in algorithms for data analysis, game mechanics, and financial calculations.

// Finding maximum and minimum values
int a = 10;
int b = 20;

int maximum = Math.Max(a, b);
int minimum = Math.Min(a, b);

Console.WriteLine("Maximum: " + maximum); // Output: 20
Console.WriteLine("Minimum: " + minimum); // Output: 10

// With different data types
double x = 15.5;
double y = 10.2;
double maxDouble = Math.Max(x, y);
Console.WriteLine("Max double: " + maxDouble); // Output: 15.5

// Practical example
int price1 = 50;
int price2 = 75;
int cheapest = Math.Min(price1, price2);
Console.WriteLine("Cheapest price: $" + cheapest); // Output: 50

Output:

Maximum: 20

Minimum: 10

Max double: 15.5

Cheapest price: $50

🔹 Square Root Method

The Math.Sqrt() method calculates the positive square root of a specified double-precision floating-point number. For instance, Math.Sqrt(64) returns 8. It's widely used in geometry (e.g., distance formulas), physics (e.g., velocity calculations), and statistics (e.g., standard deviation). The method returns double.NaN for negative inputs. Accurate square root computations are crucial in scientific computing, game development for vector math, and any domain involving quadratic equations or Euclidean distances.

// Calculating square roots
double sqrt1 = Math.Sqrt(64);
Console.WriteLine(sqrt1); // Output: 8

double sqrt2 = Math.Sqrt(25);
Console.WriteLine(sqrt2); // Output: 5

double sqrt3 = Math.Sqrt(2);
Console.WriteLine(sqrt3); // Output: 1.4142135623731

// Practical example: Pythagorean theorem
double a = 3;
double b = 4;
double c = Math.Sqrt((a * a) + (b * b));
Console.WriteLine("Hypotenuse: " + c); // Output: 5

// Square root of decimal
double sqrt4 = Math.Sqrt(15.5);
Console.WriteLine(sqrt4); // Output: 3.937003937...

Output:

8

5

1.4142135623731

Hypotenuse: 5

3.93700393700394

🔹 Absolute Value

The Math.Abs() method returns the absolute (non-negative) value of a number, effectively removing any negative sign. Example: Math.Abs(-15.5) returns 15.5. This is useful for calculating distances, differences, or magnitudes where direction is irrelevant, such as in error margin calculations, financial balance adjustments, or physics vector magnitudes. It works with various numeric types and ensures you always work with positive values in scenarios requiring magnitude-based comparisons.

// Getting absolute values
int negative = -10;
int positive = Math.Abs(negative);
Console.WriteLine(positive); // Output: 10

int alreadyPositive = 15;
int result = Math.Abs(alreadyPositive);
Console.WriteLine(result); // Output: 15

// With decimals
double negativeDouble = -25.5;
double absDouble = Math.Abs(negativeDouble);
Console.WriteLine(absDouble); // Output: 25.5

// Practical example: distance
int point1 = 10;
int point2 = 25;
int distance = Math.Abs(point1 - point2);
Console.WriteLine("Distance: " + distance); // Output: 15

Output:

10

15

25.5

Distance: 15

🔹 Rounding Methods

C# provides Math.Round(), Math.Ceiling(), and Math.Floor() for different rounding needs. Round() rounds to the nearest integer or specified decimals. Ceiling() always rounds up, while Floor() always rounds down. For example, Math.Ceiling(4.1) returns 5. These methods are critical in financial applications (currency rounding), pagination calculations, and anywhere precise numerical presentation or truncation is required to meet business or display rules.

// Different rounding methods
double number = 4.7;

double rounded = Math.Round(number);
Console.WriteLine("Round: " + rounded); // Output: 5

double ceiling = Math.Ceiling(number);
Console.WriteLine("Ceiling: " + ceiling); // Output: 5

double floor = Math.Floor(number);
Console.WriteLine("Floor: " + floor); // Output: 4

// With negative numbers
double negative = -4.7;
Console.WriteLine("Round: " + Math.Round(negative));   // Output: -5
Console.WriteLine("Ceiling: " + Math.Ceiling(negative)); // Output: -4
Console.WriteLine("Floor: " + Math.Floor(negative));   // Output: -5

// Rounding to decimal places
double price = 19.456;
double rounded2 = Math.Round(price, 2);
Console.WriteLine("Price: $" + rounded2); // Output: 19.46

Output:

Round: 5

Ceiling: 5

Floor: 4

Round: -5

Ceiling: -4

Floor: -5

Price: $19.46

🔹 Power Method

The Math.Pow() method raises a base number to a specified exponent, returning the result as a double. For example, Math.Pow(2, 3) returns 8. It's essential for exponential growth calculations (e.g., compound interest), scientific computations (e.g., decay formulas), and geometric transformations. The method handles fractional exponents for roots and negative bases with integer exponents. Accurate power computations are vital in engineering, finance, and physics simulations.

// Using Math.Pow() for exponents
double result1 = Math.Pow(2, 3);  // 2^3 = 2*2*2
Console.WriteLine(result1); // Output: 8

double result2 = Math.Pow(5, 2);  // 5^2 = 5*5
Console.WriteLine(result2); // Output: 25

double result3 = Math.Pow(10, 3); // 10^3 = 1000
Console.WriteLine(result3); // Output: 1000

// Fractional exponents (roots)
double result4 = Math.Pow(27, 1.0/3.0); // Cube root of 27
Console.WriteLine(result4); // Output: 3

// Practical example: compound interest
double principal = 1000;
double rate = 0.05; // 5%
double years = 3;
double amount = principal * Math.Pow(1 + rate, years);
Console.WriteLine("Amount: $" + Math.Round(amount, 2)); // Output: $1157.63

Output:

8

25

1000

3

Amount: $1157.63

🔹 Math Constants

The circumference of 31.42 corresponds to a circle with a radius of 5, derived from 2πr. This demonstrates the direct relationship between a circle’s radius and its perimeter, crucial in construction, manufacturing, and computer graphics. By utilizing Math.PI in code, developers can dynamically compute perimeters for various radii, ensuring precision in simulations, CAD designs, and real-world measurements without manual recalculation.

// Mathematical constants
double pi = Math.PI;
double e = Math.E;

Console.WriteLine("PI: " + pi);   // Output: 3.14159265358979
Console.WriteLine("E: " + e);     // Output: 2.71828182845905

// Using PI to calculate circle area
double radius = 5;
double area = Math.PI * Math.Pow(radius, 2);
Console.WriteLine("Circle area: " + Math.Round(area, 2)); // Output: 78.54

// Using PI to calculate circumference
double circumference = 2 * Math.PI * radius;
Console.WriteLine("Circumference: " + Math.Round(circumference, 2)); // Output: 31.42

Output:

PI: 3.14159265358979

E: 2.71828182845905

Circle area: 78.54

Circumference: 31.42

🔹 Practical Math Example

Calculating distance, such as 5 units, often involves Math.sqrt for Euclidean distance or basic arithmetic for linear measurements. This is key in navigation systems, physics simulations, and game mechanics. By leveraging operators and Math methods, developers can compute distances between coordinates, track movements, and optimize routes programmatically, ensuring accuracy in GPS technology, robotics, and spatial analysis tools.

// Practical example: Calculate circle properties
Console.WriteLine("=== Circle Calculator ===");

double radius = 7.5;
double diameter = radius * 2;
double circumference = 2 * Math.PI * radius;
double area = Math.PI * Math.Pow(radius, 2);

Console.WriteLine("Radius: " + radius);
Console.WriteLine("Diameter: " + diameter);
Console.WriteLine("Circumference: " + Math.Round(circumference, 2));
Console.WriteLine("Area: " + Math.Round(area, 2));

// Temperature conversion
Console.WriteLine("\n=== Temperature Converter ===");
double celsius = 25;
double fahrenheit = (celsius * 9/5) + 32;
Console.WriteLine(celsius + "°C = " + fahrenheit + "°F");

// Distance between two points
double x1 = 0, y1 = 0;
double x2 = 3, y2 = 4;
double distance = Math.Sqrt(Math.Pow(x2-x1, 2) + Math.Pow(y2-y1, 2));
Console.WriteLine("\nDistance: " + distance);

Output:

=== Circle Calculator ===

Radius: 7.5

Diameter: 15

Circumference: 47.12

Area: 176.71

=== Temperature Converter ===

25°C = 77°F

Distance: 5

🧠 Test Your Knowledge

What does Math.Pow(2, 4) return?