🧮 Basic Mathematical Operations

Basic mathematical operations are the building blocks of numerical computing! NumPy makes arithmetic operations on arrays as simple as working with regular numbers, but with the power to process thousands of values simultaneously. These operations form the foundation for everything from simple calculations to complex scientific algorithms.

Let's explore how to perform lightning-fast math with entire arrays!

import numpy as np

# Basic operations demonstration
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])

print(f"Array a: {a}")
print(f"Array b: {b}")

print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")

➕ Addition and Subtraction

Addition and subtraction work element-wise, combining corresponding elements from each array:

import numpy as np

# Addition and subtraction examples
prices = np.array([10.99, 25.50, 15.75, 8.25])
taxes = np.array([1.10, 2.55, 1.58, 0.83])
discounts = np.array([2.00, 5.00, 3.00, 1.00])

print(f"Prices: {prices}")
print(f"Taxes: {taxes}")
print(f"Discounts: {discounts}")

# Calculate final prices
with_tax = prices + taxes
with_discount = prices - discounts
final_price = (prices + taxes) - discounts

print(f"With tax: {with_tax}")
print(f"With discount: {with_discount}")
print(f"Final price: {final_price}")

# Operations with scalars
shipping = 5.99
total_with_shipping = final_price + shipping
print(f"Total with shipping: {total_with_shipping}")

✖️ Multiplication and Division

Multiplication and division are element-wise operations, not matrix operations:

import numpy as np

# Multiplication and division examples
quantities = np.array([2, 5, 3, 8])
unit_prices = np.array([12.50, 8.99, 15.25, 6.75])

print(f"Quantities: {quantities}")
print(f"Unit prices: {unit_prices}")

# Calculate totals
totals = quantities * unit_prices
print(f"Totals: {totals}")

# Apply bulk discount (divide by 2 for quantities > 5)
large_orders = quantities > 5
bulk_prices = np.where(large_orders, unit_prices / 2, unit_prices)
print(f"Bulk prices: {bulk_prices}")

# Division examples
print(f"Price per unit: {totals / quantities}")
print(f"Units per dollar: {quantities / unit_prices}")

# Floor division and modulo
numbers = np.array([17, 23, 31, 45])
divisor = 5
print(f"Floor division: {numbers // divisor}")
print(f"Remainder: {numbers % divisor}")

🔢 Power and Root Operations

Exponentiation and root operations are straightforward with NumPy:

import numpy as np

# Power operations
base = np.array([2, 3, 4, 5])
print(f"Base numbers: {base}")

# Exponentiation
squared = base ** 2
cubed = base ** 3
custom_power = base ** 2.5

print(f"Squared: {squared}")
print(f"Cubed: {cubed}")
print(f"Power 2.5: {custom_power}")

# Root operations
numbers = np.array([4, 9, 16, 25])
print(f"Numbers: {numbers}")

square_roots = numbers ** 0.5  # Same as np.sqrt(numbers)
cube_roots = numbers ** (1/3)

print(f"Square roots: {square_roots}")
print(f"Cube roots: {cube_roots}")

# Using NumPy functions
print(f"np.sqrt(): {np.sqrt(numbers)}")
print(f"np.power(): {np.power(base, 3)}")

🔄 Operations with Scalars

Scalars (single numbers) are automatically applied to every element in the array:

import numpy as np

# Scalar operations
scores = np.array([85, 92, 78, 96, 89])
print(f"Original scores: {scores}")

# Apply curve (add 5 points to everyone)
curved_scores = scores + 5
print(f"Curved scores: {curved_scores}")

# Apply percentage scaling (10% bonus)
bonus_scores = scores * 1.1
print(f"Bonus scores: {bonus_scores}")

# Calculate grade percentages
total_points = 100
percentages = scores / total_points * 100
print(f"Percentages: {percentages}")

# Temperature conversion example
celsius = np.array([0, 25, 37, 100])
fahrenheit = celsius * 9/5 + 32
print(f"Celsius: {celsius}")
print(f"Fahrenheit: {fahrenheit}")

📊 Combining Multiple Operations

Real calculations often involve multiple operations combined:

import numpy as np

# Complex calculation example
print("📊 Monthly Budget Analysis")
print("=" * 25)

# Monthly expenses
rent = np.array([1200, 1200, 1200, 1250])     # Months 1-4
utilities = np.array([150, 180, 140, 165])
groceries = np.array([400, 450, 380, 420])
entertainment = np.array([200, 300, 150, 250])

print(f"Rent: {rent}")
print(f"Utilities: {utilities}")
print(f"Groceries: {groceries}")
print(f"Entertainment: {entertainment}")

# Calculate total expenses
total_expenses = rent + utilities + groceries + entertainment
print(f"Total expenses: {total_expenses}")

# Monthly income
income = np.array([3500, 3500, 3600, 3500])
print(f"Income: {income}")

# Calculate savings
savings = income - total_expenses
print(f"Savings: {savings}")

# Calculate savings rate
savings_rate = (savings / income) * 100
print(f"Savings rate: {savings_rate}%")

# Compound interest on savings (monthly)
interest_rate = 0.005  # 0.5% monthly
final_savings = savings * (1 + interest_rate)
print(f"Savings with interest: {final_savings}")

⚖️ Comparison Operations

Comparison operations return boolean arrays showing where conditions are true:

import numpy as np

# Comparison operations
test_scores = np.array([85, 92, 78, 96, 89, 74, 88])
passing_grade = 80

print(f"Test scores: {test_scores}")
print(f"Passing grade: {passing_grade}")

# Boolean comparisons
passed = test_scores >= passing_grade
failed = test_scores < passing_grade
excellent = test_scores >= 90

print(f"Passed: {passed}")
print(f"Failed: {failed}")
print(f"Excellent (≥90): {excellent}")

# Using comparisons for filtering
passing_scores = test_scores[passed]
failing_scores = test_scores[failed]

print(f"Passing scores: {passing_scores}")
print(f"Failing scores: {failing_scores}")

# Counting with boolean arrays
num_passed = np.sum(passed)  # True counts as 1
num_failed = np.sum(failed)
pass_rate = np.mean(passed) * 100  # Percentage

print(f"Students passed: {num_passed}")
print(f"Students failed: {num_failed}")
print(f"Pass rate: {pass_rate:.1f}%")

🛡️ Handling Division by Zero

Division operations can encounter zero division - NumPy handles this gracefully:

import numpy as np

# Division by zero handling
numerators = np.array([10, 20, 30, 40])
denominators = np.array([2, 0, 5, 0])

print(f"Numerators: {numerators}")
print(f"Denominators: {denominators}")

# Regular division (produces warnings and inf/nan)
with np.errstate(divide='ignore', invalid='ignore'):
    result = numerators / denominators
    print(f"Division result: {result}")

# Safe division using np.divide with where parameter
safe_result = np.divide(
    numerators, 
    denominators, 
    out=np.zeros_like(numerators, dtype=float), 
    where=denominators!=0
)
print(f"Safe division: {safe_result}")

# Using np.where for conditional operations
conditional_result = np.where(
    denominators != 0, 
    numerators / denominators, 
    -1  # Default value for division by zero
)
print(f"Conditional result: {conditional_result}")

🎯 Practical Examples

Let's see basic operations solve real problems:

import numpy as np

print("🎯 Practical Mathematical Operations")
print("=" * 35)

# Example 1: Stock portfolio analysis
stock_prices = np.array([150.25, 75.80, 234.50, 89.90])
shares_owned = np.array([10, 25, 5, 40])
purchase_prices = np.array([140.00, 80.00, 220.00, 85.00])

print(f"Current prices: {stock_prices}")
print(f"Shares owned: {shares_owned}")
print(f"Purchase prices: {purchase_prices}")

# Calculate portfolio value
current_value = stock_prices * shares_owned
original_value = purchase_prices * shares_owned
profit_loss = current_value - original_value

print(f"Current value: {current_value}")
print(f"Profit/Loss: {profit_loss}")
print(f"Total portfolio: ${np.sum(current_value):.2f}")
print(f"Total P/L: ${np.sum(profit_loss):.2f}")

# Example 2: Physics calculations
print(f"\n⚡ Physics: Kinetic Energy")
masses = np.array([2.5, 1.8, 3.2, 0.9])  # kg
velocities = np.array([10, 15, 8, 25])    # m/s

# Kinetic energy: KE = 0.5 * m * v²
kinetic_energy = 0.5 * masses * velocities ** 2
print(f"Masses: {masses} kg")
print(f"Velocities: {velocities} m/s")
print(f"Kinetic energies: {kinetic_energy} J")

🎯 Key Takeaways

🚀 What's Next?

Great! You've mastered basic mathematical operations. Next, let's explore element-wise operations in more detail and discover NumPy's powerful mathematical functions.

Continue to: Element-wise Operations

Ready for advanced element operations! ⚙️✨

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent