用梯形规则Python积分函数

2024-10-05 14:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我要解决的家庭作业:

A further improvement of the approximate integration method from the last question is to divide the area under the f(x) curve into n equally-spaced trapezoids.

Based on this idea, the following formula can be derived for approximating the integral:

!(https://www.dropbox.com/s/q84mx8r5ml1q7n1/Screenshot%202017-10-01%2016.09.32.png?dl=0)!

where h is the width of the trapezoids, h=(b−a)/n, and xi=a+ih,i∈0,...,n, are the coordinates of the sides of the trapezoids. The figure above visualizes the idea of the trapezoidal rule.

Implement this formula in a Python function trapezint( f,a,b,n ). You may need to check and see if b > a, otherwise you may need to swap the variables.

For instance, the result of trapezint( math.sin,0,0.5*math.pi,10 ) should be 0.9979 (with some numerical error). The result of trapezint( abs,-1,1,10 ) should be 2.0

我的代码似乎不正确br' 对于print ((trapezint( math.sin,0,0.5*math.pi,10)))
我得到0.012286334153465965,当我得到0.9979
对于print (trapezint(abs, -1, 1, 10))
我得到0.18000000000000002,当我假设得到1.0。在

import math
def trapezint(f,a,b,n):

    g = 0
    if b>a:
        h = (b-a)/float(n)
        for i in range (0,n):
            k = 0.5*h*(f(a+i*h) + f(a + (i+1)*h))
            g = g + k
            return g
    else:
        a,b=b,a
        h = (b-a)/float(n)
        for i in range(0,n):
            k = 0.5*h*(f(a + i*h) + f(a + (i + 1)*h))
            g = g + k
            return g

print ((trapezint( math.sin,0,0.5*math.pi,10)))
print (trapezint(abs, -1, 1, 10))

Tags: ofthetoinforispimath
2条回答

这种变化降低了分支的复杂性并减少了操作的数量。最后一步的求和被简化为对数组的单个操作。在

from math import pi, sin
def trapezoid(f, a, b, n):
    if b < a:
        a,b = b, a
    h = (b - a)/float(n)
    g = [(0.5 * h * (f(a + (i * h)) + f(a  + ((i + 1) * h)))) for i in range(0, n)]
    return sum(g)

assert trapezoid(sin, 0, 0.5*pi, 10) == 0.9979429863543573
assert trapezoid(abs, -1, 1, 10) == 1.0000000000000002

实际上,您的return g语句是缩进的,而它本不应该缩进的。在

另外,我删除了您的重复代码,因此它将遵循“DRY”“Don't Repeat Yourself”原则,这可以防止错误,并使代码简化并更具可读性。在

import math
def trapezint(f, a, b, n):

    g = 0
    if b > a:
        h = (b-a)/float(n)
    else:
        h = (a-b)/float(n)

    for i in range (0, n):
        k = 0.5 * h * ( f(a + i*h) + f(a + (i+1)*h) )
        g = g + k

    return g


print ( trapezint( math.sin, 0, 0.5*math.pi, 10) )
print ( trapezint(abs, -1, 1, 10) )

0.9979429863543573
1.0000000000000002

相关问题 更多 >