COM 410 — Computer Applications in Mathematics
Computing practical sessions, code exercises, and assignment solutions walkthrough.
Module Walkthrough & Worked Programming Examples
Topics Covered: Arrays, linear algebra, and numpy.linalg operations.
Worked Example: Solving a system of linear equations ($Ax = b$) using matrix inversion and direct solvers.
import numpy as np
# Coefficients matrix A and vector b
A = np.array([[3, 1],
[1, 2]])
b = np.array([9, 8])
# 1. Solving via Matrix Inversion: x = A^(-1) * b
A_inv = np.linalg.inv(A)
x_inv = np.dot(A_inv, b)
# 2. Direct Linear Solver (Recommended)
x_solve = np.linalg.solve(A, b)
print("Inverse Method Result:", x_inv)
print("Direct Solve Result: ", x_solve)
# Output: [2. 3.]
Topics Covered: Line plots, bar charts, scatter plots, and subplots.
Worked Example: Plotting oscillating trigonometric functions on shared subplots.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
y_sin = np.sin(x)
y_cos = np.cos(x)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 5))
# Sine plot
ax1.plot(x, y_sin, color='#3b82f6', linewidth=2, label='Sine')
ax1.set_title('Sine Wave')
ax1.grid(True, linestyle='--')
# Cosine plot
ax2.plot(x, y_cos, color='#ef4444', linestyle='--', linewidth=2, label='Cosine')
ax2.set_title('Cosine Wave')
ax2.grid(True, linestyle='--')
plt.tight_layout()
plt.show()
Topics Covered: Bisection method, Newton-Raphson, and Secant Method.
Worked Example: Implementing the Newton-Raphson method to approximate roots of $f(x) = x^2 - 4 = 0$.
def f(x):
return x**2 - 4
def f_prime(x):
return 2 * x
def newton_raphson(x0, tol=1e-6, max_iter=50):
x = x0
for i in range(max_iter):
fx = f(x)
if abs(fx) < tol:
return x, i
dfx = f_prime(x)
if dfx == 0:
raise ZeroDivisionError("Derivative evaluated to zero.")
x = x - fx / dfx
return x, max_iter
root, iterations = newton_raphson(x0=3.0)
print(f"Root found: {root:.4f} in {iterations} iterations.")
# Output: Root found: 2.0000 in 4 iterations.
Topics Covered: DataFrames, descriptive stats, and hypothesis tests.
Worked Example: Creating data structures, calculating summary statistics, and performing an independent two-sample t-test.
import pandas as pd
from scipy import stats
# Dataset setup
data = {
'Control': [22, 24, 21, 25, 23, 20],
'Treatment': [28, 30, 27, 29, 31, 26]
}
df = pd.DataFrame(data)
# Summary statistics
print("--- Summary Statistics ---")
print(df.describe())
# Two-sample independent t-test
t_stat, p_value = stats.ttest_ind(df['Control'], df['Treatment'])
print(f"\nT-statistic: {t_stat:.4f}")
print(f"P-value: {p_value:.4e}")
Topics Covered: scipy.integrate.odeint and Euler's method.
Worked Example: Numerically integrating a first-order exponential decay ordinary differential equation $\frac{dy}{dt} = -k \cdot y$.
import numpy as np
from scipy.integrate import odeint
# Define ODE model
def model(y, t, k):
return -k * y
# Initial condition
y0 = 10.0
# Time vector
t = np.linspace(0, 5, 50)
# Decay constant
k = 0.5
# Solve differential equation
y = odeint(model, y0, t, args=(k,))
print("First 5 calculated values of y(t):")
print(y[:5].flatten())