Lesson 2 of 15

Euler Integration

Euler Integration

A single Euler step gives one point. To approximate an entire trajectory, we repeat the step nn times from t0t_0 to tendt_{\text{end}}.

Algorithm

def euler(f, t0, y0, t_end, n):
    h = (t_end - t0) / n
    t, y = t0, y0
    ys = [y0]
    for _ in range(n):
        y = y + h * f(t, y)
        t += h
        ys.append(y)
    return ys

The step size is h=(tendt0)/nh = (t_{\text{end}} - t_0) / n. Smaller hh (more steps) gives higher accuracy, at the cost of more computation.

Accuracy vs. Step Size

Euler's method has first-order accuracy: if you halve hh, the global error halves too. For the ODE dydt=y\frac{dy}{dt} = y with y(0)=1y(0) = 1:

n stepsy(1) approximationexact e ≈ 2.71828
102.59372.71828
1002.70482.71828
10002.71692.71828

Your Task

Implement euler(f, t0, y0, t_end, n) that returns a list of n+1n+1 values (including the initial value).

Pyodide loading...
Loading...
Click "Run" to execute your code.