1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| from termcolor import cprint
from typing import List, Callable
import numpy as np
from scipy.integrate import simps
def rectangles(f: Callable, a: int, b: int, n: int) -> float:
"""Intégrale d'une fonction par la méthode des rectangles"""
S = 0
for i in range(0, n):
Xi = a + (b - a) * i/float(n)
Xj = a + (b - a) * (i + 1)/float(n)
S += f((Xi + Xj)/2.0) * (Xj - Xi)
return S
def trapezes(f: Callable, a: int, b: int, n: int) -> float:
"""Intégrale d'une fonction par la méthode des trapèzes"""
S = 0
for i in range(0, n):
Xi = a + (b - a) * i/float(n)
Xj = a + (b - a) * (i + 1)/float(n)
S += (f(Xi) + f(Xj))/2.0 * (Xj - Xi)
return S
def simpson(f: Callable, a: int, b: int, n: int) -> float:
"""Intégrale d'une fonction par la méthode de simpson"""
S = 0
for i in range(0, n):
Xi = a + (b - a) * i/float(n)
Xj = a + (b - a) * (i + 1)/float(n)
S += (Xj - Xi) * (f(Xi) + 4.0*f((Xi + Xj)/2.0) + f(Xj))/6.0
return S
a: int = 0
b: int = 2
n: int = 500
def fn(x: float) -> float:
"""Fonction à intégrer"""
return np.exp(x)
cprint('rectangles = {}'.format(rectangles(fn, a, b, n)), 'green')
cprint('trapezes = {}'.format(trapezes(fn, a, b, n)), 'green')
cprint('simpson = {}'.format(simpson(fn, a, b, n)), 'green')
# debug
X: List[float] = []
Y: List[float] = []
h: float = (b - a)/n
for x in np.arange(a, b + h, h):
X.append(x)
Y.append(fn(x))
cprint('debug simpson = {}'.format(simps(Y, X)), 'red')
'''
rectangles = 6.38905183956191
trapezes = 6.38906461766984
simpson = 6.389056098931216
debug simpson = 6.3890560989397365
''' |