python3积分

绘图

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as sci
from matplotlib.patches import Polygon

def f(x):
    return np.sin(x) + 0.5*x
a = 0.5
b = 9.5
x = np.linspace(0,10)
y = f(x)

fig,ax = plt.subplots(figsize = (7,5))
plt.plot(x,y,'b',linewidth=2)
plt.ylim(ymin=0)

ix = np.linspace(a,b)
iy = f(ix)
verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)]
poly = Polygon(verts,facecolor='0.7',edgecolor='0.5')
ax.add_patch(poly)

plt.text(0.75*(a+b),1.5, r"$\int_a^b  f(x)dx$",horizontalalignment='center' ,  fontsize=20)
plt.figtext(0.9 ,  0.075 ,  '$x$')
plt.figtext(0.075 ,  0.9 ,  '$f(x)$')

ax.set_xticks((a,b))
ax.set_xticklabels(('$a$','$b$'))
ax.set_yticks([f(a),f(b)])
plt.show()

求积算法

g = sci.fixed_quad(f,a,b)[0]
print('高斯求积:'+str(g))
z = sci.quad(f,a,b)[0]
print('自适应求积:'+str(z))
r = sci.romberg(f,a,b)
print('龙贝格求积:'+str(r))
高斯求积:24.366995967084602
自适应求积:24.374754718086752
龙贝格求积:24.374754718086713

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/Da___Vinci/article/details/88823816