Thuta Learning
Python
IntermediateProgrammingBeginner

SciPy Tutorial (Enhanced)

PythonLesson 3635 min

What you'll walk away with

  • Import SciPy submodules explicitly, for example from scipy import optimize
  • Read the results of integrate.quad and optimize.minimize_scalar, including error estimates and success flags
  • Solve a linear system with linalg.solve instead of computing an inverse
  • Summarise data and fit a line with stats, and pass the sampling rate fs correctly to signal.periodogram

Explain it simply

SciPy in plain language

NumPy gives you arrays and basic maths; SciPy is the toolbox of scientific and engineering algorithms that work on those arrays. Areas under curves, the lowest point of a function, systems of equations, statistical tests and the frequencies inside a signal are all handled by well-tested routines.

Think of it as a calculator with specialist buttons: you do not write the algorithm, you choose the right button and supply the inputs. The answers are numerical approximations, though, so checking how accurate they are and whether the algorithm succeeded is still your job.

Problem → Why → Solution

The problem: hand-written numerical code is fragile

Suppose you estimate the area under x² from 0 to 1 by adding up rectangles in a loop. With 10 slices you get 0.285 instead of 0.3333, and pushing to millions of slices gets slow. Worse, the code never tells you how wrong the answer is. Home-made loops for finding minima or solving equations share the same weaknesses.

area_by_hand.py
n = 10
width = 1 / n
area = 0.0
for i in range(n):
    x = i * width          # left edge of each slice
    area += x**2 * width

print(area)   # 0.285 - but how far from the truth? the loop cannot say

What SciPy gives you instead

integrate.quad(lambda x: x**2, 0, 1) uses an adaptive algorithm that returns 0.333333 together with an error estimate, so you know how much to trust it. SciPy's routines wrap Fortran and C libraries tested over decades, which makes them fast and already hardened against edge cases.

Core concept: submodules, result objects and tolerances

SciPy is split into submodules by kind of task. Rather than relying on a bare import scipy to expose everything, the clear and conventional style is to import what you need explicitly, as in from scipy import optimize, stats. The table lists the submodules this lesson uses.

SubmoduleTypical functionsUsed for
integratequad, trapezoid, solve_ivpintegrals and differential equations
optimizeminimize, minimize_scalar, brentq, curve_fitminima, roots, curve fitting
linalgsolve, det, eigmatrices and linear systems
statsdescribe, mode, linregress, normstatistics and distributions
signalperiodogram, butter, find_peakssignal processing

Most functions return an object describing the result rather than a bare number. optimize.minimize_scalar returns an OptimizeResult: .x is the answer, .fun is the function value there, and .success with .message tell you whether the algorithm actually converged. integrate.quad returns a (value, abserr) tuple, so unpack it and look at the error estimate.

Answers are floating-point approximations, so a value you expect to be 1.8 may be 1.7999999999999998. Compare with np.allclose instead of == and format numbers for display. Most optimizers are local methods that find the nearest valley from the starting point; on a function with many valleys, nothing guarantees the global minimum.

Choosing a routine depends on what kind of input you have. If you have a Python function you can call at any x, quad picks as many points as it needs by itself. If all you have is an array of samples from a sensor, integrate the area between those points with integrate.trapezoid instead. In the same way, use minimize_scalar for one variable, minimize with a starting array x0 for several, and brentq when you want where a function crosses zero rather than where it is lowest.

Every SciPy call is ask, answer, verify
  1. Pick the submodule for the task
  2. Pass a function plus range or start
  3. Unpack the result object
  4. Verify: success, error or allclose

Every numerical answer carries the question of how far to trust it; the result object is where that answer lives.

General pattern

python
from scipy import integrate, linalg, optimize, stats

value, abserr = integrate.quad(f, lower, upper)
res = optimize.minimize_scalar(f)                 # res.x, res.fun, res.success
res = optimize.minimize(f, x0=start_guess)        # several variables
root = optimize.brentq(f, a, b)                   # f(a) and f(b) differ in sign
x = linalg.solve(A, b)                            # A @ x == b
fit = stats.linregress(xs, ys)                    # fit.slope, fit.intercept

Express the maths as a Python function or array, hand it to the matching routine, and read both the answer and the diagnostics from the returned tuple or result object.

Worked example: one call from each of five submodules

The program below uses each of five submodules on a problem whose answer is known in advance: the integral of x² is 1/3, (x - 3)² + 1 is lowest at x = 3, and the linear system's solution is (1.8, 0.8). Knowing the answers lets you confirm that SciPy's output can be trusted. The final part recovers the 10 Hz and 25 Hz components of a signal sampled at 100 Hz.

scipy_tour.py
import numpy as np
from scipy import integrate, linalg, optimize, signal, stats

# 1. Integration: area under x**2 from 0 to 1 (exact answer 1/3)
area, err_estimate = integrate.quad(lambda x: x**2, 0, 1)
print(f"quad: {area:.6f} (error estimate < 1e-10: {err_estimate < 1e-10})")

# 2. Optimization: minimum of (x - 3)**2 + 1
best = optimize.minimize_scalar(lambda x: (x - 3) ** 2 + 1)
print(f"minimize_scalar: x = {best.x:.4f}, f(x) = {best.fun:.4f}")

# 3. Linear algebra: 3x + 2y = 7 and x + 4y = 5
A = np.array([[3.0, 2.0], [1.0, 4.0]])
b = np.array([7.0, 5.0])
x = linalg.solve(A, b)
print("solve:", x, "check A @ x == b:", np.allclose(A @ x, b))

# 4. Statistics: summary and a fitted straight line
data = np.array([2, 4, 4, 4, 5, 5, 7, 9])
print("mode:", stats.mode(data).mode, "std (ddof=0):", np.std(data))
hours = np.array([1, 2, 3, 4, 5])
marks = np.array([52, 57, 61, 68, 72])
fit = stats.linregress(hours, marks)
print(f"linregress: slope = {fit.slope:.2f}, r = {fit.rvalue:.3f}")

# 5. Signal: which frequencies are in a 1-second recording at 100 Hz?
fs = 100
t = np.arange(fs) / fs
wave = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 25 * t)
freqs, power = signal.periodogram(wave, fs=fs)
peaks = freqs[np.argsort(power)[-2:]]
print("strongest frequencies (Hz):", sorted(peaks.tolist()))

Code breakdown

  1. Integratearea, err_estimate = integrate.quad(lambda x: x**2, 0, 1)

    quad returns a tuple, so the value and the error estimate are unpacked separately. The estimate is far below 1e-10, which is why 0.333333 can be trusted.

  2. Minimize one variablebest = optimize.minimize_scalar(lambda x: (x - 3) ** 2 + 1)

    For a function of one variable, minimize_scalar is the simple choice: best.x is 3.0 and best.fun is 1.0. With several variables you would use optimize.minimize with a starting guess.

  3. Solve, then checkx = linalg.solve(A, b)

    Solves 3x + 2y = 7 and x + 4y = 5 written as A @ x = b. The same print line confirms the answer by substituting it back with np.allclose(A @ x, b).

  4. Fit a linefit = stats.linregress(hours, marks)

    linregress returns an object with slope, intercept, rvalue and more. Each extra study hour adds about 5.10 marks, and r = 0.996 shows a very strong linear relationship.

  5. Pass the sampling ratefreqs, power = signal.periodogram(wave, fs=fs)

    Because fs=100 is passed, freqs comes back in hertz. Without it the default fs of 1.0 is used, frequencies are in cycles per sample, and the 10 Hz peak shows up as 0.1 instead.

You should see
quad: 0.333333 (error estimate < 1e-10: True)
minimize_scalar: x = 3.0000, f(x) = 1.0000
solve: [1.8 0.8] check A @ x == b: True
mode: 4 std (ddof=0): 2.0
linregress: slope = 5.10, r = 0.996
strongest frequencies (Hz): [10.0, 25.0]

Root finding and curve fitting

Finding the x where f(x) = 0 is called root finding. optimize.brentq(f, a, b) requires f to have opposite signs at a and b, which guarantees a root in between and makes it very reliable. If the signs match it raises ValueError, a useful signal that your bracket is wrong.

optimize.curve_fit finds the parameters of a model function that best match measured data, using least squares. Passing a sensible starting guess with p0 helps it avoid a wrong local solution. The mini challenge uses both functions.

In real projects

SciPy in real projects

SciPy is not only for research labs; product teams use it too. Even when you never import it directly, libraries such as scikit-learn and statsmodels rely on SciPy's optimizers and linear algebra internally. In application code it usually lives inside a small, well-tested function whose inputs and outputs are plain arrays.

  • A/B testing: compare conversion data for two versions with stats.ttest_ind or a chi-square test to decide whether a difference is real or just chance.
  • Engineering and IoT: analyse vibration sensor data with signal.periodogram and watch for frequency peaks that appear before a machine fails, passing the sensor's real sample rate as fs.
  • Pricing and logistics: minimise a cost function with optimize.minimize, adding bounds and constraints for real-world limits.

Common mistakes

Common SciPy mistakes

Forgetting fs in signal functions

periodogram, welch and similar functions default to fs=1.0. Without the real sampling rate, the returned frequencies are in cycles per sample, not hertz, so you see values like 0, 0.002, 0.004. Nothing raises an error, so a mislabelled axis easily slips through.

Trusting a result without checking it

optimize.minimize returns a result even when it fails to converge; no exception is raised. Check res.success and res.message, and try two or three different starting points to see whether they agree.

Computing an inverse and multiplying

linalg.inv(A) @ b gives an answer, but it is slower and less accurate. linalg.solve(A, b) solves the system directly and raises a clear LinAlgError for a singular matrix.

Mixing up population and sample standard deviation

np.std(data) uses ddof=0 by default, the population formula. When estimating from a sample, pass ddof=1; note that pandas' .std() already defaults to ddof=1.

Best practices

Best practices

  • Test each routine on a simple case with a known answer before trusting it on real data.
  • Log the success flag, message and error estimate from result objects.
  • Record units such as seconds, hertz or metres in variable names or comments.
  • Give optimizers bounds and a sensible starting guess to narrow the search.

Mini challenge

Mini challenge: a ball thrown upward

A ball is thrown upward at 20 m/s from 1.5 m, so its height is h(t) = 1.5 + 20t - 4.9t². Use SciPy to find when it lands, the peak height and its time, and the average height while airborne. Finally recover v0 and g from six measured points with curve_fit.

  • Find the landing time with optimize.brentq (the bracket must change sign)
  • Find the peak by minimising -h(t) with a bounded minimize_scalar
  • Average height = quad integral divided by flight time
  • Use curve_fit with a p0 guess and print v0 and g to 2 decimal places
ball.py
import numpy as np
from scipy import integrate, optimize


def height(t: float, v0: float = 20.0, h0: float = 1.5) -> float:
    return h0 + v0 * t - 4.9 * t**2


# TODO 1: landing = optimize.brentq(...) on a bracket where height changes sign
# TODO 2: peak = optimize.minimize_scalar(...) on the NEGATIVE height,
#         bounded to [0, landing]
# TODO 3: average height = integral of height over [0, landing] / landing


def model(t, v0, g):
    # TODO 4: same physics with v0 and g as unknown parameters
    ...


times = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5])
measured = np.array([1.5, 10.3, 16.6, 20.5, 21.9, 20.9])
# TODO 5: fit model to the measurements with optimize.curve_fit and print v0, g

Expected: lands after 4.155 s, peak 21.91 m at t = 2.041 s, average height 14.85 m, and fitted v0 = 20.01 m/s with g = 9.81 m/s^2.

Show hint

h is positive at t = 1 and negative at t = 10, so (1, 10) is a good bracket. The optimizer only minimises, so negate the function to find the maximum and negate .fun back.

Show solution
ball.py
import numpy as np
from scipy import integrate, optimize


def height(t: float, v0: float = 20.0, h0: float = 1.5) -> float:
    """Height (m) of a ball thrown straight up, t seconds after launch."""
    return h0 + v0 * t - 4.9 * t**2


# 1. When does it land? Find the root of height(t) between 1 s and 10 s.
landing = optimize.brentq(height, 1, 10)

# 2. Highest point: minimize the NEGATIVE height inside [0, landing].
peak = optimize.minimize_scalar(lambda t: -height(t), bounds=(0, landing),
                                method="bounded")

# 3. Average height while in the air = integral / flight time.
area, _ = integrate.quad(height, 0, landing)

print(f"lands after {landing:.3f} s")
print(f"peak {-peak.fun:.2f} m at t = {peak.x:.3f} s")
print(f"average height {area / landing:.2f} m")


# 4. Recover v0 and g from measured points with curve_fit.
def model(t, v0, g):
    return 1.5 + v0 * t - 0.5 * g * t**2


times = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5])
measured = np.array([1.5, 10.3, 16.6, 20.5, 21.9, 20.9])
(v0_fit, g_fit), _ = optimize.curve_fit(model, times, measured, p0=[10, 5])
print(f"fitted v0 = {v0_fit:.2f} m/s, g = {g_fit:.2f} m/s^2")

Quick quiz 1 / 3

You write value = integrate.quad(f, 0, 1) and then compute value * 2. What happens?

Quick quiz 2 / 3

Data sampled at 1000 Hz is passed to signal.periodogram(data) without fs. At what value does a 50 Hz peak appear in freqs?

Quick quiz 3 / 3

What is the best way to solve A @ x = b?

What to remember

  • SciPy adds algorithms on top of NumPy arrays, grouped into submodules such as integrate, optimize, linalg, stats and signal.
  • Most functions return a tuple or a result object; unpack it and check success flags and error estimates.
  • Solve linear systems with linalg.solve, not with inv().
  • Always pass fs to signal functions; without it, frequencies are not in hertz.

SciPy — User Guide — SciPy

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

SciPy Tutorial (Enhanced) | Thuta Learning