TExcelTAD
Home › Calculus in Depth › Graphing with Computers

Graphing with Computers

A plotting library draws a graph by evaluating the function at finitely many points and joining them with straight segments. That is usually fine and sometimes badly misleading. This lesson covers viewing windows, sampling and aliasing, fake lines across asymptotes, and families of functions, so you can trust what the screen shows you, or know when not to.

Plotting itself is covered in Matplotlib Plotting; here we are concerned with the mathematics of what a plot can and cannot show.

How a plot is made

plt.plot(x, f(x)) with x = np.linspace(a, b, n) does three things: it samples ff at nn equally spaced points, connects consecutive samples with line segments, and maps the viewing rectangle [a,b]×[c,d][a, b] \times [c, d] onto the screen. Each step can hide the truth:

Problem Cause Remedy
a feature is invisible window too large or too small try several windows, zoom on interesting points
a wave looks slower than it is too few samples (aliasing) more samples than twice the frequency, ideally far more
a vertical line at an asymptote segments join +∞+\infty and −∞-\infty samples mask large values, or split the domain
two functions look identical only the dominant term is visible at large scale compare on a smaller window or plot the difference
a graph misses part of its domain odd roots computed as complex numbers use np.cbrt or sign-aware formulas

Sampling and aliasing

If a function oscillates faster than the sampling rate can resolve, the samples line up with a different, slower wave. This is aliasing, and it is the same effect that makes wagon wheels spin backwards in films.

python · try it yourself
import numpy as np

t = np.arange(10) / 10            # 10 samples per second over 1 s
fast = np.sin(2 * np.pi * 11 * t) # an 11 Hz wave
slow = np.sin(2 * np.pi * 1 * t)  # a 1 Hz wave
print(np.round(fast, 4))
print(np.round(slow, 4))
print("identical samples:", bool(np.allclose(fast, slow)))
[ 0.      0.5878  0.9511  0.9511  0.5878  0.     -0.5878 -0.9511 -0.9511
 -0.5878]
[ 0.      0.5878  0.9511  0.9511  0.5878  0.     -0.5878 -0.9511 -0.9511
 -0.5878]
identical samples: True

At 10 samples per second, an 11 Hz signal is indistinguishable from a 1 Hz one, because sin⁡(2π⋅11⋅k/10)=sin⁡(2π⋅k+2π⋅k/10)=sin⁡(2π⋅k/10)\sin(2\pi \cdot 11 \cdot k/10) = \sin(2\pi \cdot k + 2\pi \cdot k/10) = \sin(2\pi \cdot k/10). The Nyquist–Shannon sampling theorem says you need more than two samples per period to recover a sine wave; for a graph that also looks smooth, use dozens.

Asymptotes and fake vertical lines

Plotting tan⁡x\tan x on [0,2π][0, 2\pi] joins a huge positive sample just left of π/2\pi/2 to a huge negative sample just right of it, drawing a vertical line that is not part of the graph. The fix is to break the line where the values are too large, by replacing them with NaN (Matplotlib leaves gaps at NaN):

python · try it yourself
import numpy as np

x = np.linspace(0, 2 * np.pi, 1000)
y = np.tan(x)
jumps = int(np.sum((np.abs(np.diff(y)) > 50) & (y[:-1] * y[1:] < 0)))
y_masked = np.where(np.abs(y) > 10, np.nan, y)
print("huge jumps that flip sign:", jumps)
print("points hidden:", int(np.isnan(y_masked).sum()), "of", y.size)
huge jumps that flip sign: 2
points hidden: 64 of 1000

The two sign-flipping jumps are the asymptotes at π/2\pi/2 and 3π/23\pi/2 (other neighbours near an asymptote also differ by a lot, but stay on the same side). A window of y∈[−10,10]y \in [-10, 10] then shows the correct picture.

Windows: local and global behaviour

No single window shows everything. Large windows show end behaviour, dominated by the leading term; small windows show roots, turning points and inflection points. On [−1000,1000][-1000, 1000], p(x)=x4−4x3p(x) = x^4 - 4x^3 and q(x)=x4q(x) = x^4 look the same, since p(x)/q(x)=1−4/x→1p(x)/q(x) = 1 - 4/x \to 1, yet near the origin pp has a root at 4 and a minimum at x=3x = 3 that qq lacks. A reliable workflow is to compute the interesting points first (where f=0f = 0, and later where f′=0f' = 0 and f′′=0f'' = 0) and then choose a window that contains them.

Families of functions

Plotting a function for several values of a parameter shows how the parameter changes the shape. In the family f(x)=x3+cxf(x) = x^3 + cx, the turning points appear only for negative cc:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2.5, 2.5, 500)
plt.figure(figsize=(6, 4))
for c in [-3, -1, 0, 1, 3]:
    plt.plot(x, x**3 + c * x, label=f"c = {c}")
plt.ylim(-6, 6)
plt.axhline(0, color="grey", lw=0.5)
plt.legend()
plt.title("The family x³ + cx")
for c in [-3, -1, 0, 1, 3]:
    y = x**3 + c * x
    turns = int(np.sum(np.diff(np.sign(np.diff(y))) != 0))
    print(f"c = {c:>2}: turning points = {turns}")
c = -3: turning points = 2
c = -1: turning points = 2
c =  0: turning points = 0
c =  1: turning points = 0
c =  3: turning points = 0

For c<0c < 0 the turning points sit at x=±−c/3x = \pm\sqrt{-c/3}; as cc rises to 0 they merge and disappear. Chapter 4 proves this with the derivative 3x2+c3x^2 + c.

Graphs as a tool for solving equations

Counting where two graphs cross is a quick way to count the solutions of an equation, and sign changes in the sampled difference give starting brackets for an exact root finder. A plot finds candidates; a proof or a careful numeric method confirms them. Missing a root that sits between two samples (a "double touch" where ff has no sign change) is a classic failure.

In software

Everyone who draws data meets these issues: dashboards that downsample a time series can hide spikes (an aliasing effect), audio code must low-pass filter before resampling, games that sample collisions once per frame can let a fast object pass through a wall ("tunnelling"), and log-scaled axes (Ticks and Scales) are the standard way to show quantities that span orders of magnitude.

Exercises

Exercise 1: Predict the alias

A 9 Hz sine wave is sampled 10 times per second. Which frequency do the samples appear to have, and with which sign?

Answer

It looks like a 1 Hz wave with the opposite sign: sin⁡(2π⋅9⋅k/10)=−sin⁡(2π⋅k/10)\sin(2\pi \cdot 9 \cdot k/10) = -\sin(2\pi \cdot k/10).

Solution
sin⁡(2π⋅9k/10)=sin⁡(2πk−2πk/10)=sin⁡(−2πk/10)=−sin⁡(2π⋅k/10)\sin(2\pi \cdot 9k/10) = \sin(2\pi k - 2\pi k/10) = \sin(-2\pi k/10) = -\sin(2\pi \cdot k/10)

The apparent frequency is ∣9−10∣=1 Hz\lvert 9 - 10 \rvert = 1\ \text{Hz}, and the wave is mirrored (like a wheel turning backwards).

Exercise 2: Choose a window

Find a viewing rectangle that shows all roots and both turning points of f(x)=x3−30x2+200xf(x) = x^3 - 30x^2 + 200x.

Answer

For example x∈[−2,22]x \in [-2, 22], y∈[−450,450]y \in [-450, 450]. Roots at 0, 10, 20; turning points near x≈4.23x \approx 4.23 (y≈385y \approx 385) and x≈15.77x \approx 15.77 (y≈−385y \approx -385).

Solution

f(x)=x(x2−30x+200)=x(x−10)(x−20)f(x) = x(x^2 - 30x + 200) = x(x - 10)(x - 20), so the roots are 0, 10 and 20. The turning points solve 3x2−60x+200=03x^2 - 60x + 200 = 0 (from chapter 3's derivative, or read off a rough plot):

x=60±3600−24006=10±103≈4.226 and 15.774f(4.226)≈384.9,f(15.774)≈−384.9\begin{aligned} x &= \frac{60 \pm \sqrt{3600 - 2400}}{6} = 10 \pm \frac{10}{\sqrt{3}} \approx 4.226 \text{ and } 15.774 \\ f(4.226) &\approx 384.9, \qquad f(15.774) \approx -384.9 \end{aligned}

The graph is symmetric about the middle root (10,0)(10, 0), which is why the two values are opposites.

Exercise 3: Count solutions with a sampled graph

How many solutions does cos⁡x=x/10\cos x = x/10 have? Use sign changes of cos⁡x−x/10\cos x - x/10 on a fine grid. Explain why it is enough to search −10≤x≤10-10 \le x \le 10.

Answer

7 solutions, near −9.68, −8.97, −4.27, −1.75, 1.43, 5.27 and 7.07.

Solution

∣cos⁡x∣≤1\lvert \cos x \rvert \le 1, so a solution needs ∣x/10∣≤1\lvert x/10 \rvert \le 1, that is ∣x∣≤10\lvert x \rvert \le 10.

python · try it yourself
import numpy as np

x = np.linspace(-10, 10, 200001)
s = np.sign(np.cos(x) - x / 10)
idx = np.where(s[:-1] * s[1:] < 0)[0]
print(len(idx), [round(float(x[i]), 2) for i in idx])
7 [-9.68, -8.97, -4.27, -1.75, 1.43, 5.27, 7.07]

A grid this fine could still miss a tangential touch, but none occurs here: near each crossing the two graphs meet at a clear angle.

Exercise 4: Where does the family turn?

For which values of cc does x3+cxx^3 + cx have two turning points? Check c=−12c = -12 by finding them.

Answer

For c<0c < 0. For c=−12c = -12 they are at x=±2x = \pm 2.

Solution

As the plot suggests, turning points exist only when the cubic dips: they are at x=±−c/3x = \pm\sqrt{-c/3}, which is real and nonzero only for c<0c < 0. For c=−12c = -12: x=±4=±2x = \pm\sqrt{4} = \pm 2, with f(2)=8−24=−16f(2) = 8 - 24 = -16 and f(−2)=16f(-2) = 16.

Test yourself

Why can plotting tan⁡x\tan x produce vertical lines at x=π/2x = \pi/2?

  1. tan⁡\tan is discontinuous everywhere
  2. The plotter joins a large positive sample to a large negative one across the asymptote
  3. Matplotlib cannot compute tan
  4. The window is too small

Sampled 10 times per second, an 11 Hz sine looks like which wave?

  1. 1 Hz
  2. 11 Hz
  3. 21 Hz
  4. a constant

On a huge window x4−4x3x^4 - 4x^3 and x4x^4 look the same. Why?

  1. They are equal
  2. Their ratio tends to 1 because the leading term dominates
  3. Plotting errors
  4. Both are even