Mathématiques en première générale – Algorithmes

Construction de l'exponentielle
par la méthode d'Euler

def euler_exp(a, n) :
    x, y = 0, 1
    lx, ly = [x], [y]
    h = a / n
    for i in range(n) :
        x += h
        y *= 1 + h
        lx.append(x)
        ly.append(y)
    return ly[n], lx, ly

import numpy as np
import matplotlib.pyplot as plt
from math import exp
def plot(n, a, lx, ly) :
    lxx = np.linspace(0, a, 50)
    plt.figure()
    plt.plot(lxx, [exp(x) for x in lxx],
                label="exp", color="green", zorder=1)
    plt.scatter(lx, ly,
                label="Euler", color="red", s=7, zorder=2)
    plt.legend()
    plt.savefig("figure_{}.svg".format(n))

def run(a, n) :
    expa, lx, ly = euler_exp(a, n)
    plot(n, a, lx, ly)
    return expa

a = 1
print(run(a, 5))
print(run(a, 50))
print(exp(a))
2.48832
2.6915880290736074
2.718281828459045
Lionel Avon