復化求積公式
阿新 • • 發佈:2018-11-19
一、簡介
復化求積公式(composite integration rule )一類重要的求積公式,指將求積區間分為n個子區間,對每個子區間應用同一求積公式,所得到的複合數值積分公式。
二、實現
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 19 10:21:15 2016
復化梯形、復化Simpson
@author: Administrator
"""
from numpy import *
from scipy import integrate
import matplotlib.pyplot as plt
#x [0,2pi]
def f(x):
return e**(3*x) * cos(pi * x)
def T(a,b,n=50):
h = (b - a) / n
temp = 0
for i in range(1,n):
x = a + i * h
temp += 2 * f(x)
return (b - a) / (2 * n) * (f(a) + temp + f(b))
#50 100 200 500 1000
def S(a,b,n=50):
h = (b - a) / n
temp1 = 0
temp2 = 0
for i in range(1,n):
xk1 = a + h * i
xk2 = a + h * (i + 1)
xk12 = (xk1 + xk2) / 2
temp1 += f(xk1)
temp2 += f(xk12)
temp2 += f((a + a + h) / 2)
return (b - a) / (6 * n) * (f(a) + 4 * temp2 + 2 * temp1 + f(b))
if __name__ == '__main__':
n =1000 #50 100 200 500 1000
a = 0
b = 2 * pi
print 'Truth-value:',integrate.quad(f,a,b)[0]
print 'T-Estimated-value:',T(a,b,n)
print 'S-Estimated-value:',S(a,b,n)
x = linspace(0,2*pi,100)
y = f(x)
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.plot(x,y,color='r',linestyle='-',label='f(x)')
ax.legend(loc='upper left')
fig.show()
fig.savefig('a.png')