数值积分,求解圆周率[Scipy]

求解圆周率

  • integrate 对函数(1 - x^2)^0.5进行积分
  • # s = pi*r**2
    # r = 1
    # s = pi
    # 求解圆的面积------>圆周率
x = np.linspace(-1,1,200)

# x**2 + y**2 = 1 ——> 半径是1
# y = (1 - X**2)**0.5

y = (1 - x**2)**0.5
y
Out:
array([0.        , 0.14141957, 0.19949179, 0.24370564, 0.28068824,
       0.3130133 , 0.34200401, 0.3684483 , 0.39286071, 0.41559946,
       0.43692593, 0.45703787, 0.47608922, 0.49420265, 0.51147782,
       0.52799701, 0.54382912, 0.55903252, 0.57365721, 0.58774639,
………………

# plot绘制
plt.figure(figsize=(4,4))
plt.plot(x,y)
plt.plot(x,-y)

f = lambda x :(1 - x**2)**0.5
type(f)
Out:
function
  1. X2 + Y2 = 1,半径是1
  2. pi×r**2,只要求得面积--->求出pi即可求s
  3. 圆的面积是?

使用scipy.integrate进行积分,调用quad()方法

导入

import scipy.integrate as integrate

使用积分求解的圆周率及误差

ret,err = integrate.quad(f,-1,1)
print('使用积分求解的圆周率:%s;误差是:%s'%(str(ret*2),str(err)))
Out:
使用积分求解的圆周率:3.141592653589797;误差是:1.0002356720661965e-09

 

猜你喜欢

转载自blog.csdn.net/Dorisi_H_n_q/article/details/82584575
今日推荐