Linear interpolation
Linear interpolation (lesson 1.6.1)
0 of 8 correct
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
How to type answers
- Powers with
^:x^7,2^(1/3),a^-2. - Multiply with
*or by writing side by side:3x^2,2(x+1). ln(x)is the natural log,log(x, 2)is log base 2,eis Euler's number,sqrt(x)is a square root.sin(x),cos(x)andtan(x)take radians; writepifor π andsin(x)^2for sin²x.- Your first answer to each question is saved: it counts towards your score and brings the question back for review.
- Exact answers like
ln(20)/ln(3)are best. Decimals need about 4 significant figures.
Cubic splines
Cubic splines (lesson 1.6.2)
0 of 8 correct
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
How to type answers
- Powers with
^:x^7,2^(1/3),a^-2. - Multiply with
*or by writing side by side:3x^2,2(x+1). ln(x)is the natural log,log(x, 2)is log base 2,eis Euler's number,sqrt(x)is a square root.sin(x),cos(x)andtan(x)take radians; writepifor π andsin(x)^2for sin²x.- Your first answer to each question is saved: it counts towards your score and brings the question back for review.
- Exact answers like
ln(20)/ln(3)are best. Decimals need about 4 significant figures.
Coding exercise
Linear interpolation from scratch
Write interpolate(xs, ys, x) that returns the linear interpolation of the points (xs[i], ys[i]) at a single number x. The xs are in increasing order, but not always evenly spaced.
- Find the two neighbours with
xs[i] <= x <= xs[i + 1], then use the formula from lesson 1.6.1 with that gap's own width. - If
xis outside[xs[0], xs[-1]], raiseValueError: refuse to extrapolate, unlikenp.interp.
The tests compare your answers with np.interp inside the data.
See the tests
import numpy as np
XS = [0, 1, 2, 4]
YS = [1, 3, 2, 6]
def test_between_two_points():
"""Halfway between (0, 1) and (1, 3) gives 2"""
expect_close(interpolate(XS, YS, 0.5), 2.0, what="interpolate at 0.5")
def test_picks_the_right_gap():
"""At x = 3 it uses (2, 2) and (4, 6), giving 4"""
expect_close(interpolate(XS, YS, 3), 4.0, what="interpolate at 3")
def test_at_known_points():
"""At a known point it returns that point's value"""
for x, y in zip(XS, YS):
expect_close(interpolate(XS, YS, x), y, what=f"interpolate at {x}")
def test_matches_numpy():
"""Agrees with np.interp at many points inside the data"""
for x in np.linspace(0, 4, 37):
expect_close(interpolate(XS, YS, x), np.interp(x, XS, YS), what=f"interpolate at {x:.3f}")
def test_refuses_to_extrapolate():
"""Outside the data, raise ValueError"""
for x in (-1, 5):
try:
interpolate(XS, YS, x)
except ValueError:
continue
raise AssertionError(f"expected ValueError at x = {x}")