🧮 Mathematical Operations

Python provides extensive mathematical capabilities through built-in functions and the math module, enabling you to perform complex calculations, statistical analysis, and scientific computing. These tools are essential for data analysis, financial calculations, scientific research, and many other applications.

Think of Python's mathematical functions as a comprehensive scientific calculator - from basic trigonometry to advanced statistical operations, you have powerful computational tools at your fingertips for solving real-world problems.

import math
import statistics

# Basic mathematical functions
numbers = [10, 15, 20, 25, 30]

# Statistical calculations
mean_value = statistics.mean(numbers)
median_value = statistics.median(numbers)
std_dev = statistics.stdev(numbers)

print(f"Data: {numbers}")
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Standard Deviation: {std_dev:.2f}")

# Advanced math functions
angle = math.pi / 4  # 45 degrees in radians
print(f"\nTrigonometry for {math.degrees(angle)} degrees:")
print(f"Sine: {math.sin(angle):.3f}")
print(f"Cosine: {math.cos(angle):.3f}")
print(f"Tangent: {math.tan(angle):.3f}")

# Logarithmic and exponential
value = 100
print(f"\nLogarithmic operations for {value}:")
print(f"Natural log: {math.log(value):.3f}")
print(f"Log base 10: {math.log10(value):.3f}")
print(f"Exponential: {math.exp(2):.3f}")

🎯 Python's Mathematical Ecosystem

Python offers multiple layers of mathematical functionality, from basic arithmetic to advanced scientific computing libraries.

Basic Mathematical Functions

Built-in functions and operators provide the foundation for mathematical operations in Python.

import math

# Basic arithmetic and built-in functions
numbers = [4.7, -3.2, 8.9, -1.5, 6.3]

print("Basic Operations:")
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
print(f"Max: {max(numbers)}")
print(f"Min: {min(numbers)}")
print(f"Absolute values: {[abs(x) for x in numbers]}")

# Rounding and precision
value = 3.14159265359
print(f"\nRounding operations for {value}:")
print(f"Round to 2 decimals: {round(value, 2)}")
print(f"Round to nearest integer: {round(value)}")
print(f"Floor (round down): {math.floor(value)}")
print(f"Ceiling (round up): {math.ceil(value)}")
print(f"Truncate (remove decimals): {math.trunc(value)}")

# Power and root operations
base = 16
print(f"\nPower and root operations for {base}:")
print(f"Square: {base ** 2}")
print(f"Cube: {base ** 3}")
print(f"Square root: {math.sqrt(base)}")
print(f"Cube root: {base ** (1/3):.3f}")
print(f"4th root: {base ** (1/4):.3f}")

# Modulo and division
dividend = 17
divisor = 5
print(f"\nDivision operations: {dividend} ÷ {divisor}")
print(f"Regular division: {dividend / divisor}")
print(f"Floor division: {dividend // divisor}")
print(f"Modulo (remainder): {dividend % divisor}")
print(f"Divmod (quotient, remainder): {divmod(dividend, divisor)}")

⚡ Trigonometric Functions

Trigonometric functions are essential for geometry, physics, engineering, and many scientific applications.

import math

# Convert between degrees and radians
def degrees_to_radians(degrees):
    return math.radians(degrees)

def radians_to_degrees(radians):
    return math.degrees(radians)

# Common angles in degrees and their trigonometric values
angles_degrees = [0, 30, 45, 60, 90, 180, 270, 360]

print("Trigonometric Functions:")
print("Angle (°) | Radians | Sin     | Cos     | Tan")
print("-" * 50)

for degrees in angles_degrees:
    radians = degrees_to_radians(degrees)
    
    # Handle special cases for tangent
    if degrees in [90, 270]:
        tan_value = "undefined"
    else:
        tan_value = f"{math.tan(radians):7.3f}"
    
    print(f"{degrees:7} | {radians:7.3f} | {math.sin(radians):7.3f} | "
          f"{math.cos(radians):7.3f} | {tan_value}")

# Inverse trigonometric functions
print("\nInverse Trigonometric Functions:")
value = 0.5
print(f"arcsin({value}) = {math.degrees(math.asin(value)):.1f}°")
print(f"arccos({value}) = {math.degrees(math.acos(value)):.1f}°")
print(f"arctan({value}) = {math.degrees(math.atan(value)):.1f}°")

# Practical example: Calculate distance using Law of Cosines
def calculate_distance(a, b, angle_degrees):
    """Calculate the third side of a triangle using Law of Cosines"""
    angle_radians = math.radians(angle_degrees)
    c_squared = a**2 + b**2 - 2*a*b*math.cos(angle_radians)
    return math.sqrt(c_squared)

# Find distance between two points
side_a = 10  # meters
side_b = 15  # meters
angle = 120  # degrees

distance = calculate_distance(side_a, side_b, angle)
print(f"\nTriangle with sides {side_a}m and {side_b}m, angle {angle}°:")
print(f"Third side length: {distance:.2f}m")

🚀 Logarithmic and Exponential Functions

Logarithmic and exponential functions are crucial for growth calculations, data analysis, and scientific modeling.

import math

# Exponential functions
print("Exponential Functions:")
for x in [0, 1, 2, 3]:
    print(f"e^{x} = {math.exp(x):.3f}")

print(f"\nEuler's number (e): {math.e:.6f}")

# Logarithmic functions
values = [1, 2, 10, 100, 1000]
print("\nLogarithmic Functions:")
print("Value | ln(x)   | log10(x) | log2(x)")
print("-" * 40)

for value in values:
    ln_x = math.log(value)
    log10_x = math.log10(value)
    log2_x = math.log2(value)
    print(f"{value:5} | {ln_x:7.3f} | {log10_x:8.3f} | {log2_x:7.3f}")

# Practical applications
def compound_interest(principal, rate, time, n=1):
    """Calculate compound interest: A = P(1 + r/n)^(nt)"""
    amount = principal * math.pow((1 + rate/n), n * time)
    return amount

def exponential_growth(initial, growth_rate, time):
    """Calculate exponential growth: N(t) = N0 * e^(rt)"""
    return initial * math.exp(growth_rate * time)

def half_life_decay(initial, half_life, time):
    """Calculate radioactive decay using half-life"""
    decay_constant = math.log(2) / half_life
    return initial * math.exp(-decay_constant * time)

# Financial calculation
principal = 1000  # Initial investment
rate = 0.05      # 5% annual interest
time = 10        # 10 years
final_amount = compound_interest(principal, rate, time, 12)  # Monthly compounding

print(f"\nCompound Interest Calculation:")
print(f"Initial investment: ${principal}")
print(f"Interest rate: {rate*100}% annually")
print(f"Time: {time} years")
print(f"Final amount: ${final_amount:.2f}")
print(f"Total interest: ${final_amount - principal:.2f}")

# Population growth
initial_population = 1000
growth_rate = 0.02  # 2% per year
years = 20
future_population = exponential_growth(initial_population, growth_rate, years)

print(f"\nPopulation Growth:")
print(f"Initial population: {initial_population}")
print(f"Growth rate: {growth_rate*100}% per year")
print(f"Population after {years} years: {future_population:.0f}")

🌟 Statistical Analysis

Python's statistics module provides powerful tools for data analysis and statistical calculations.

Central Tendency and Spread

Measure the center and variability of your data with built-in statistical functions.

import statistics
import math

# Sample data: test scores
test_scores = [85, 92, 78, 96, 88, 83, 91, 87, 94, 89, 82, 95]
sales_data = [150, 200, 175, 300, 225, 180, 195, 210, 165, 240]

print("Test Scores Analysis:")
print(f"Data: {test_scores}")
print(f"Mean: {statistics.mean(test_scores):.1f}")
print(f"Median: {statistics.median(test_scores)}")
print(f"Mode: {statistics.mode(test_scores)}")

# Measures of spread
print(f"\nMeasures of Spread:")
print(f"Standard Deviation: {statistics.stdev(test_scores):.2f}")
print(f"Variance: {statistics.variance(test_scores):.2f}")
print(f"Range: {max(test_scores) - min(test_scores)}")

# Quartiles and percentiles
print(f"\nQuartiles:")
quartiles = statistics.quantiles(test_scores, n=4)
print(f"Q1 (25th percentile): {quartiles[0]:.1f}")
print(f"Q2 (50th percentile): {statistics.median(test_scores):.1f}")
print(f"Q3 (75th percentile): {quartiles[2]:.1f}")

# Custom statistical functions
def coefficient_of_variation(data):
    """Calculate coefficient of variation (CV)"""
    mean = statistics.mean(data)
    stdev = statistics.stdev(data)
    return (stdev / mean) * 100

def z_score(value, data):
    """Calculate z-score for a value in a dataset"""
    mean = statistics.mean(data)
    stdev = statistics.stdev(data)
    return (value - mean) / stdev

print(f"\nAdvanced Statistics:")
print(f"Coefficient of Variation: {coefficient_of_variation(test_scores):.1f}%")
print(f"Z-score for 95: {z_score(95, test_scores):.2f}")

# Compare two datasets
print(f"\nComparison with Sales Data:")
print(f"Sales CV: {coefficient_of_variation(sales_data):.1f}%")
print(f"Test Scores CV: {coefficient_of_variation(test_scores):.1f}%")
print("Sales data has" + (" more" if coefficient_of_variation(sales_data) > coefficient_of_variation(test_scores) else " less") + " variability")

Correlation and Regression

Analyze relationships between variables using correlation and basic regression techniques.

import statistics
import math

def correlation(x_data, y_data):
    """Calculate Pearson correlation coefficient"""
    if len(x_data) != len(y_data):
        raise ValueError("Data sets must have the same length")
    
    n = len(x_data)
    if n < 2:
        raise ValueError("Need at least 2 data points")
    
    # Calculate means
    x_mean = statistics.mean(x_data)
    y_mean = statistics.mean(y_data)
    
    # Calculate correlation coefficient
    numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_data, y_data))
    x_variance = sum((x - x_mean) ** 2 for x in x_data)
    y_variance = sum((y - y_mean) ** 2 for y in y_data)
    
    denominator = math.sqrt(x_variance * y_variance)
    
    if denominator == 0:
        return 0  # No correlation if no variance
    
    return numerator / denominator

def linear_regression(x_data, y_data):
    """Calculate linear regression slope and intercept"""
    if len(x_data) != len(y_data):
        raise ValueError("Data sets must have the same length")
    
    n = len(x_data)
    x_mean = statistics.mean(x_data)
    y_mean = statistics.mean(y_data)
    
    # Calculate slope (m) and intercept (b) for y = mx + b
    numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_data, y_data))
    denominator = sum((x - x_mean) ** 2 for x in x_data)
    
    if denominator == 0:
        raise ValueError("Cannot calculate regression - no variance in x")
    
    slope = numerator / denominator
    intercept = y_mean - slope * x_mean
    
    return slope, intercept

# Example: Study hours vs test scores
study_hours = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
test_scores = [65, 70, 75, 80, 85, 88, 92, 95, 97, 99]

# Calculate correlation
corr = correlation(study_hours, test_scores)
print(f"Study Hours vs Test Scores Analysis:")
print(f"Study Hours: {study_hours}")
print(f"Test Scores: {test_scores}")
print(f"Correlation: {corr:.3f}")

# Interpret correlation
if abs(corr) > 0.8:
    strength = "strong"
elif abs(corr) > 0.5:
    strength = "moderate"
else:
    strength = "weak"

direction = "positive" if corr > 0 else "negative"
print(f"This indicates a {strength} {direction} relationship")

# Linear regression
slope, intercept = linear_regression(study_hours, test_scores)
print(f"\nLinear Regression:")
print(f"Equation: y = {slope:.2f}x + {intercept:.2f}")
print(f"For every additional hour of study, scores increase by {slope:.2f} points")

# Predict scores for new study hours
new_hours = [5, 15, 22]
print(f"\nPredictions:")
for hours in new_hours:
    predicted_score = slope * hours + intercept
    print(f"{hours} hours of study: {predicted_score:.1f} points")

💡 Real-World Mathematical Applications

Financial Calculations

Apply mathematical functions to solve practical financial problems.

import math

class FinancialCalculator:
    """A comprehensive financial calculator using mathematical operations"""
    
    @staticmethod
    def compound_interest(principal, annual_rate, years, compounds_per_year=1):
        """Calculate compound interest with flexible compounding periods"""
        amount = principal * math.pow((1 + annual_rate/compounds_per_year), 
                                    compounds_per_year * years)
        return round(amount, 2)
    
    @staticmethod
    def loan_payment(principal, annual_rate, years):
        """Calculate monthly loan payment using present value formula"""
        monthly_rate = annual_rate / 12
        num_payments = years * 12
        
        if monthly_rate == 0:  # Handle 0% interest rate
            return principal / num_payments
        
        payment = principal * (monthly_rate * math.pow(1 + monthly_rate, num_payments)) / \
                 (math.pow(1 + monthly_rate, num_payments) - 1)
        return round(payment, 2)
    
    @staticmethod
    def future_value_annuity(payment, annual_rate, years):
        """Calculate future value of regular payments"""
        monthly_rate = annual_rate / 12
        num_payments = years * 12
        
        if monthly_rate == 0:
            return payment * num_payments
        
        fv = payment * ((math.pow(1 + monthly_rate, num_payments) - 1) / monthly_rate)
        return round(fv, 2)
    
    @staticmethod
    def retirement_planning(current_age, retirement_age, current_savings, 
                          monthly_contribution, annual_return):
        """Calculate retirement savings projection"""
        years_to_retirement = retirement_age - current_age
        
        # Future value of current savings
        current_savings_fv = current_savings * math.pow(1 + annual_return, years_to_retirement)
        
        # Future value of monthly contributions
        contributions_fv = FinancialCalculator.future_value_annuity(
            monthly_contribution, annual_return, years_to_retirement)
        
        total_retirement_fund = current_savings_fv + contributions_fv
        return round(total_retirement_fund, 2)

# Financial planning examples
calc = FinancialCalculator()

print("Financial Planning Calculations:")

# Investment comparison
principal = 10000
rate = 0.07  # 7% annual return
years = 30

# Different compounding frequencies
annual_compound = calc.compound_interest(principal, rate, years, 1)
monthly_compound = calc.compound_interest(principal, rate, years, 12)
daily_compound = calc.compound_interest(principal, rate, years, 365)

print(f"\nInvestment of ${principal:,} at {rate*100}% for {years} years:")
print(f"Annual compounding: ${annual_compound:,}")
print(f"Monthly compounding: ${monthly_compound:,}")
print(f"Daily compounding: ${daily_compound:,}")
print(f"Difference (daily vs annual): ${daily_compound - annual_compound:,}")

# Loan analysis
loan_amount = 250000  # Home loan
loan_rate = 0.045     # 4.5% annual rate
loan_years = 30

monthly_payment = calc.loan_payment(loan_amount, loan_rate, loan_years)
total_paid = monthly_payment * 12 * loan_years
total_interest = total_paid - loan_amount

print(f"\nHome Loan Analysis:")
print(f"Loan amount: ${loan_amount:,}")
print(f"Interest rate: {loan_rate*100}%")
print(f"Term: {loan_years} years")
print(f"Monthly payment: ${monthly_payment:,}")
print(f"Total interest: ${total_interest:,}")

# Retirement planning
retirement_fund = calc.retirement_planning(
    current_age=30,
    retirement_age=65,
    current_savings=25000,
    monthly_contribution=1000,
    annual_return=0.08
)

print(f"\nRetirement Planning:")
print(f"Starting at age 30 with ${25000:,}")
print(f"Contributing ${1000:,}/month until age 65")
print(f"Expected 8% annual return")
print(f"Projected retirement fund: ${retirement_fund:,}")

Hands-on Exercise

Create a simple grade calculator that calculates the average of test scores and determines the letter grade. Use mathematical operations to find the mean, round to appropriate decimal places, and assign letter grades based on score ranges.

python
import math

def calculate_grade_info(test_scores):
    # TODO: Calculate the average score
    # TODO: Round to 2 decimal places
    # TODO: Determine letter grade based on average
    # TODO: Find highest and lowest scores
    # TODO: Calculate the standard deviation (optional)
    # TODO: Return all information
    pass

def assign_letter_grade(average):
    # TODO: Assign letter grade based on score ranges
    # A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60
    pass

# TODO: Test with sample scores
test_scores = [85, 92, 78, 96, 88, 91, 82]

result = calculate_grade_info(test_scores)
print(f"Test scores: {test_scores}")
print(f"Average: {result['average']}")
print(f"Letter grade: {result['letter_grade']}")
print(f"Highest score: {result['highest']}")
print(f"Lowest score: {result['lowest']}")

Solution and Explanation 💡

Click to see the complete solution
import math

def calculate_grade_info(test_scores):
    # Calculate the average score
    average = sum(test_scores) / len(test_scores)
    
    # Round to 2 decimal places
    average = round(average, 2)
    
    # Determine letter grade based on average
    letter_grade = assign_letter_grade(average)
    
    # Find highest and lowest scores
    highest = max(test_scores)
    lowest = min(test_scores)
    
    # Calculate the standard deviation (bonus)
    mean = average
    variance = sum((score - mean) ** 2 for score in test_scores) / len(test_scores)
    std_deviation = round(math.sqrt(variance), 2)
    
    # Return all information
    return {
        'average': average,
        'letter_grade': letter_grade,
        'highest': highest,
        'lowest': lowest,
        'std_deviation': std_deviation
    }

def assign_letter_grade(average):
    # Assign letter grade based on score ranges
    if average >= 90:
        return 'A'
    elif average >= 80:
        return 'B'
    elif average >= 70:
        return 'C'
    elif average >= 60:
        return 'D'
    else:
        return 'F'

# Test with sample scores
test_scores = [85, 92, 78, 96, 88, 91, 82]

result = calculate_grade_info(test_scores)
print(f"Test scores: {test_scores}")
print(f"Average: {result['average']}")
print(f"Letter grade: {result['letter_grade']}")
print(f"Highest score: {result['highest']}")
print(f"Lowest score: {result['lowest']}")
print(f"Standard deviation: {result['std_deviation']}")

Key Learning Points:

  • 📌 Basic arithmetic: Use sum(), len(), max(), min() for calculations
  • 📌 Division and averages: Simple division gives precise average
  • 📌 Rounding: Use round() function to control decimal places
  • 📌 Math module: Use math.sqrt() for square root calculations
  • 📌 Conditional logic: Use if/elif statements for grade assignment

Learn more about JSON data to handle structured data in your mathematical applications.

Test Your Knowledge

Test what you've learned about mathematical operations:

What's Next?

Now that you can perform complex mathematical operations, you're ready to explore JSON data handling. Learn how to work with structured data formats that are essential for APIs, configuration files, and data exchange in modern applications.

Ready to continue? Check out our lesson on JSON Data.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent