TExcelTAD
Home › SciPy › SciPy Exercises

SciPy Exercises

Time to practise! Each exercise has a starter playground that runs as-is and prints placeholder results, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution — but give it a real try first.

# Exercise Subpackage
1 Unit conversions scipy.constants
2 The cheapest soda can scipy.optimize (minimize)
3 Solve e⁻ˣ = x scipy.optimize (roots)
4 Computing π with an integral scipy.integrate (quad)
5 When does the population reach 500? scipy.integrate (solve_ivp)
6 Fit a power law scipy.optimize (curve_fit)
7 Morning or evening exam? scipy.stats
8 Hidden frequencies scipy.fft

1. Unit conversions

Using only scipy.constants (no typed-in conversion factors), print:

  • the marathon distance, 42.195 km, in miles (3 decimals),
  • a height of 5 ft 11 in, in metres (4 decimals),
  • the boiling point of water, 212 °F, in kelvin (2 decimals).

Expected:

text
marathon: 26.219 miles
height  : 1.8034 m
boiling : 373.15 K
python · try it yourself
from scipy import constants

marathon_miles = 0.0   # TODO: use constants.kilo and constants.mile
height_m = 0.0         # TODO: use constants.foot and constants.inch
boiling_k = 0.0        # TODO: use constants.convert_temperature

print(f"marathon: {marathon_miles:.3f} miles")
print(f"height  : {height_m:.4f} m")
print(f"boiling : {boiling_k:.2f} K")
marathon: 0.000 miles
height  : 0.0000 m
boiling : 0.00 K
Show solution
python
from scipy import constants

marathon_miles = 42.195 * constants.kilo / constants.mile
height_m = 5 * constants.foot + 11 * constants.inch
boiling_k = constants.convert_temperature(212, "F", "K")

print(f"marathon: {marathon_miles:.3f} miles")
print(f"height  : {height_m:.4f} m")
print(f"boiling : {boiling_k:.2f} K")

Unit constants are "how many SI units one of this unit is", so multiply to convert to SI and divide to convert from it.

2. The cheapest soda can

A cylindrical can must hold 330 cm³. Its surface area (top, bottom and side) is 2πr² + 2πrh, and the volume fixes the height: h = 330 / (πr²). Find the radius that minimises the material used, searching between 1 and 10 cm.

Expected: r = 3.745 cm, h = 7.490 cm, area = 264.36 cm^2 (notice that the best height is exactly twice the radius).

python · try it yourself
import numpy as np
from scipy.optimize import minimize_scalar

V = 330

def area(r):
    h = V / (np.pi * r ** 2)
    return 0.0   # TODO: return the surface area

# TODO: minimize area with a bounded search between 1 and 10
r = 1.0
h = V / (np.pi * r ** 2)
print(f"r = {r:.3f} cm, h = {h:.3f} cm, area = {area(r):.2f} cm^2")
r = 1.000 cm, h = 105.042 cm, area = 0.00 cm^2
Show solution
python
import numpy as np
from scipy.optimize import minimize_scalar

V = 330

def area(r):
    h = V / (np.pi * r ** 2)
    return 2 * np.pi * r ** 2 + 2 * np.pi * r * h

res = minimize_scalar(area, bounds=(1, 10), method="bounded")
r = res.x
h = V / (np.pi * r ** 2)
print(f"r = {r:.3f} cm, h = {h:.3f} cm, area = {res.fun:.2f} cm^2")

3. Solve e⁻ˣ = x

Rewrite the equation as f(x) = e⁻ˣ − x = 0 and find the root with brentq. First check that f(0) and f(1) have opposite signs, so [0, 1] is a valid bracket.

Expected:

text
f(0) = 1.0, f(1) = -0.632
x = 0.567143
python · try it yourself
import numpy as np
from scipy.optimize import brentq

def f(x):
    return 0.0   # TODO

print(f"f(0) = {f(0)}, f(1) = {f(1):.3f}")
x = 0.0          # TODO: use brentq on [0, 1]
print(f"x = {x:.6f}")
f(0) = 0.0, f(1) = 0.000
x = 0.000000
Show solution
python
import numpy as np
from scipy.optimize import brentq

def f(x):
    return np.exp(-x) - x

print(f"f(0) = {f(0)}, f(1) = {f(1):.3f}")
x = brentq(f, 0, 1)
print(f"x = {x:.6f}")

This number, 0.567143…, is known as the omega constant.

4. Computing π with an integral

The integral of 1 / (1 + x²) from 0 to 1 equals π/4. Use quad to compute it, multiply by 4 and print the result with 10 decimals, plus the absolute difference from np.pi.

Expected:

text
4 * integral = 3.1415926536
difference   < 1e-12: True
python · try it yourself
import numpy as np
from scipy.integrate import quad

value = 0.0   # TODO: integrate 1 / (1 + x**2) from 0 to 1

print(f"4 * integral = {4 * value:.10f}")
print("difference   < 1e-12:", abs(4 * value - np.pi) < 1e-12)
4 * integral = 0.0000000000
difference   < 1e-12: False
Show solution
python
import numpy as np
from scipy.integrate import quad

value, err = quad(lambda x: 1 / (1 + x ** 2), 0, 1)

print(f"4 * integral = {4 * value:.10f}")
print("difference   < 1e-12:", abs(4 * value - np.pi) < 1e-12)

5. When does the population reach 500?

A population follows the logistic equation dP/dt = 0.3 · P · (1 − P/1000) starting from P(0) = 10. Use solve_ivp with an event that stops the solver when P reaches 500, and print that time. Use rtol=1e-9, atol=1e-9. Compare with the exact answer ln(99) / 0.3.

Expected:

text
reaches 500 at t = 15.317
exact            : 15.317
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

def growth(t, P):
    return [0.0]   # TODO: the logistic equation

def reaches_500(t, P):
    return 1.0     # TODO: zero when P == 500
reaches_500.terminal = True

sol = solve_ivp(growth, (0, 50), [10], events=reaches_500, rtol=1e-9, atol=1e-9)
times = sol.t_events[0]
print("reaches 500 at t =", f"{times[0]:.3f}" if times.size else "never")
print(f"exact            : {np.log(99) / 0.3:.3f}")
reaches 500 at t = never
exact            : 15.317
Show solution
python
import numpy as np
from scipy.integrate import solve_ivp

def growth(t, P):
    return 0.3 * P * (1 - P / 1000)

def reaches_500(t, P):
    return P[0] - 500
reaches_500.terminal = True

sol = solve_ivp(growth, (0, 50), [10], events=reaches_500, rtol=1e-9, atol=1e-9)
times = sol.t_events[0]
print("reaches 500 at t =", f"{times[0]:.3f}" if times.size else "never")
print(f"exact            : {np.log(99) / 0.3:.3f}")

terminal = True stops the integration at the first event, so the solver doesn't waste time after the answer is known.

6. Fit a power law

Fit the model y = a · x^b to the data below with curve_fit (start from p0=[1, 1]), print a and b with 3 decimals and predict y at x = 10.

Expected:

text
a = 2.038, b = 1.487
prediction at x = 10: 62.5
python · try it yourself
import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 4, 5, 6], dtype=float)
y = np.array([2.1, 5.5, 10.6, 15.8, 22.6, 29.1])

def power(x, a, b):
    return a * x ** b

a, b = 1.0, 1.0   # TODO: fit the model
print(f"a = {a:.3f}, b = {b:.3f}")
print(f"prediction at x = 10: {power(10, a, b):.1f}")
a = 1.000, b = 1.000
prediction at x = 10: 10.0
Show solution
python
import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 4, 5, 6], dtype=float)
y = np.array([2.1, 5.5, 10.6, 15.8, 22.6, 29.1])

def power(x, a, b):
    return a * x ** b

(a, b), cov = curve_fit(power, x, y, p0=[1, 1])
print(f"a = {a:.3f}, b = {b:.3f}")
print(f"prediction at x = 10: {power(10, a, b):.1f}")

7. Morning or evening exam?

Two groups took the same exam, one in the morning and one in the evening. Use Welch's t-test to decide, at the 5% level, whether the mean scores differ.

Expected:

text
morning mean 79.6, evening mean 72.5
t = 5.087, p = 0.00020
significant: True
python · try it yourself
import numpy as np
from scipy import stats

morning = np.array([78, 82, 75, 80, 85, 79, 81, 77])
evening = np.array([72, 74, 70, 76, 73, 71, 75, 69])

t, p = 0.0, 1.0   # TODO: run the test

print(f"morning mean {morning.mean():.1f}, evening mean {evening.mean():.1f}")
print(f"t = {t:.3f}, p = {p:.5f}")
print("significant:", p < 0.05)
morning mean 79.6, evening mean 72.5
t = 0.000, p = 1.00000
significant: False
Show solution
python
import numpy as np
from scipy import stats

morning = np.array([78, 82, 75, 80, 85, 79, 81, 77])
evening = np.array([72, 74, 70, 76, 73, 71, 75, 69])

res = stats.ttest_ind(morning, evening, equal_var=False)
t, p = res.statistic, res.pvalue

print(f"morning mean {morning.mean():.1f}, evening mean {evening.mean():.1f}")
print(f"t = {t:.3f}, p = {p:.5f}")
print("significant:", p < 0.05)

equal_var=False selects Welch's version, which doesn't assume both groups have the same variance.

8. Hidden frequencies

The signal below contains two sine tones buried in noise. Use rfft and rfftfreq to find the two strongest frequencies, sorted in ascending order.

Expected: two strongest: [37. 85.] Hz

python · try it yourself
import numpy as np
from scipy.fft import rfft, rfftfreq

fs = 400
t = np.arange(0, 2, 1 / fs)
rng = np.random.default_rng(5)
x = (0.7 * np.sin(2 * np.pi * 37 * t) + 0.3 * np.sin(2 * np.pi * 85 * t)
     + rng.normal(0, 0.5, t.size))

top2 = np.array([0.0, 0.0])   # TODO: FFT, then pick the two largest amplitudes
print("two strongest:", top2, "Hz")
two strongest: [0. 0.] Hz
Show solution
python
import numpy as np
from scipy.fft import rfft, rfftfreq

fs = 400
t = np.arange(0, 2, 1 / fs)
rng = np.random.default_rng(5)
x = (0.7 * np.sin(2 * np.pi * 37 * t) + 0.3 * np.sin(2 * np.pi * 85 * t)
     + rng.normal(0, 0.5, t.size))

amplitude = np.abs(rfft(x))
freqs = rfftfreq(x.size, d=1 / fs)
top2 = np.sort(freqs[np.argsort(amplitude)[-2:]])
print("two strongest:", top2, "Hz")

np.argsort sorts from smallest to largest, so the last two indices belong to the two largest amplitudes.

Test yourself

In exercise 2, which method lets minimize_scalar search only between 1 and 10?

  1. method='brent'
  2. method='bounded' with bounds=(1, 10)
  3. method='golden'
  4. x0=5

What does setting event.terminal = True do in solve_ivp?

  1. Prints the event time
  2. Stops the integration when the event occurs
  3. Makes the event happen at t = 0
  4. Ignores the event

Why can't brentq find a root on [0, 1] if f(0) and f(1) have the same sign?

  1. brentq needs a derivative
  2. Without a sign change the interval isn't a valid bracket
  3. brentq only works for polynomials
  4. It can — signs don't matter