python实现分步长的Simpson求积法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_45026221/article/details/100548949

用分步长的Simpson算法计算积分
可以指定误差eps,如要修改函数则修改fun(x)

from sympy import *
import math


def fun(x):
    return cos(x)


def inte_ran_step(fun,u_lim,l_lim,eps):
    state = 1
    N = 2
    while state:
        step_length = (u_lim - l_lim) / N
        S1 = 0
        T1 = 0
        T2 = 0
        for i in range(N + 1):
            if i == 0 or i == N:
                S1 += (fun(l_lim + step_length*i))/2 * step_length
            else:
                S1 += (fun(l_lim + step_length*i)) * step_length
        S2 = S1/2
        for i in range(N):
            S2 += step_length/2 * fun(l_lim + (i + 1/2) * step_length)
        S4 = S2/2
        for i in range(N):
            S4 += step_length/2 * fun(l_lim + (i + 1/2) * step_length)
        T1 = 4/3 * S2 -1/3 * S1
        T2 = 4/3 * S4 - 1/3 * S2
        if abs(T2 - T1) < eps:
            print('The accurte integrate is ' + str(T1))
            print('N = ' + str(N))
            state = 0
        else:
            N += 2


if __name__ == '__main__':
    u_lim = input('input upper limit:')
    l_lim = input('input lower limit:')
    eps = input('input eps:')
    u_lim = float(u_lim)
    l_lim = float(l_lim)
    eps = float(eps)
    inte_ran_step(fun,u_lim,l_lim,eps)

猜你喜欢

转载自blog.csdn.net/qq_45026221/article/details/100548949
今日推荐