python scipy 求函数定积分
"""
定积分处理 求函数 起始==>终止的面积
"""
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.patches as mc
import scipy.integrate as si
def f(x):
return 2 * x ** 2 + 3 * x + 4
a, b = -5, 5
x = np.linspace(-5, 5, 1000)
y = f(x)
mp.grid(linestyle=":")
mp.plot(x, y, color="dodgerblue", linewidth=5)
n = 50
px = np.linspace(a, b, n + 1)
py = f(px)
area = 0
for i in range(n):
area += (py[i + 1] + py[i]) * (px[i + 1] - px[i]) / 2
print(area)
result = si.quad(f, a, b)
print(result)
for i in range(n):
mp.gca().add_patch(mc.Polygon([
[px[i], 0], [px[i], py[i]],
[px[i + 1], py[i + 1]], [px[i + 1], 0]],
fc="deepskyblue", ec="dodgerblue", alpha=0.5
))
mp.show()