问题描述
我想用midpoint_rule
函数在[0到2pi]范围内计算sin ^ 2(x)的积分。代码可以使用此参数print(midpoint_rule(np.sin,2*np.pi,1000))
计算sin(x),但是当我将np.sin
更改为此np.sin**2
时,我将在底部看到错误。我该如何解决这个问题?
def midpoint_rule(f,a,b,num_intervals):
"""
integrate function f using the midpoint rule
Args:
f: function to be integrated
a: lower bound of integral range
b: upper bound of integral range
num_intervals: the number of intervals in [a,b]
Returns:
compute the integral
"""
L = (b-a) #how big is the range
dx = L/num_intervals #how big is each interval
midpoints = np.arange(num_intervals)*dx+0.5*dx+a
integral = 0
for point in midpoints:
integral = integral + f(point)
return integral*dx
print(midpoint_rule(np.sin**2,1000))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-57-a71b452963dc> in <module>
26 return integral*dx
27
---> 28 print(midpoint_rule(np.sin**2,1000))
TypeError: unsupported operand type(s) for ** or pow(): 'numpy.ufunc' and 'int'
解决方法
lambda函数完成任务。
import numpy as np
def midpoint_rule(f,a,b,num_intervals):
"""
integrate function f using the midpoint rule
Args:
f: function to be integrated
a: lower bound of integral range
b: upper bound of integral range
num_intervals: the number of intervals in [a,b]
Returns:
compute the integral
"""
L = (b-a) #how big is the range
dx = L/num_intervals #how big is each interval
midpoints = np.arange(num_intervals)*dx+0.5*dx+a
integral = 0
for point in midpoints:
integral = integral + f(point)
return integral*dx
print(midpoint_rule(lambda x: np.sin(x)**2,2*np.pi,1000))
,
我了解问题所在,您想将np.sin
作为函数传递,我的建议是使用np.sin
而不是f
,并完全删除f
。
for point in midpoints:
integral = integral + np.sin(point) ** 2
return integral * dx
然后打印功能
print(midpoint_rule(0,2 * np.pi,1000))
输出:
3.141592653589793