下面是我要解决的家庭作业:
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
, andxi=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 oftrapezint( 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))
这种变化降低了分支的复杂性并减少了操作的数量。最后一步的求和被简化为对数组的单个操作。在
实际上,您的
return g
语句是缩进的,而它本不应该缩进的。在另外,我删除了您的重复代码,因此它将遵循“DRY”“Don't Repeat Yourself”原则,这可以防止错误,并使代码简化并更具可读性。在
相关问题 更多 >
编程相关推荐