微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在函数中获取numpy.sin的平方?

如何解决如何在函数中获取numpy.sin的平方?

我想用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。