python实现分步长的Simpson求积法

用分步长的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 = float(input('input upper limit:'))
    l_lim = float(input('input lower limit:'))
    eps = float(input('input eps:'))
    inte_ran_step(fun,u_lim,l_lim,eps)
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值