简体   繁体   English

将数学方程式作为参数传递(numpy)

[英]Passing a math equation as an argument (numpy)

I am looking to write a program that calculates the left+right riemann sum of a function. 我正在寻找一个程序来计算函数的左右riemann和。 My only problem is, I want the function to take np.sin(x^2) or np.cos(3*x +2) or perhaps ax^2 + 3*x + 2 (polynomial function) as the y parameter and np.linspace() as the x parameter and 'left' or 'right' as a string. 我唯一的问题是,我希望函数将np.sin(x ^ 2)或np.cos(3 * x +2)或ax ^ 2 + 3 * x + 2(多项式函数)作为y参数,并将np.linspace()作为x参数,“ left”或“ right”作为字符串。 So far, my code does take sin(x) / cos(x) to calculate the left/right riemann sum of those 2 function. 到目前为止,我的代码确实使用sin(x)/ cos(x)来计算这两个函数的左/右riemann和。 But I am struggling to let's say pass a function like sin(x^2)+3 and take it's approximation. 但是我很难说通过sin(x ^ 2)+3之类的函数并将其作为近似值。 I have the logic of the equation right but perhaps, I'm not understanding the data structures of numpy/python really well. 我有正确的等式逻辑,但也许我不太了解numpy / python的数据结构。 Here is my code: 这是我的代码:

import numpy as np
def r_sums(y,x,method='left'):
    #f = y(x)
    l = []
    delta_x = abs(x[0]-x[-1])/len(x)
    while method != 'right':
        #Calculating Left Riemann Sum (below the list comprehension is a normal for loop of the list comprehension func)
        return sum([ y(x[0]+ i*delta_x) for i in range(0,len(x))])*delta_x
        #for i in range(0,len(x)):
            #f_a = x[0] + i*(delta_x) #Calculating left endpoint
            #l.append(y(f_a))         #Appends all the left endpoint into a list l
        #return sum(l)*delta_x

    #Calculating Right Riemann Sum (below the list comprehension is a normal for loop of the list comprehension func)
    return sum([y(x[0]+ i*delta_x) for i in range(1,len(x)+1)])*delta_x
    #for i in range(1,len(x)+1):
        #f_a = x[0] + i*(delta_x)
        #l.append(y(f_a))
    #return sum(l)*delta_x

r_sums(np.sin,np.linspace(1,4,200),'left') should work but I am looking to have the y parameter to take something like r_sums(np.sin,np.linspace(1,4,200),'left')应该可以工作,但是我正在寻找y参数来采取类似

r_sums(np.sin(x**2+3),np.linspace(1,4,200),'left') <-- doesn't work r_sums(np.sin(x ** 2 + 3),np.linspace(1,4,200),'left')<-不起作用

Really appreciate some help/feedback! 非常感谢您的帮助/反馈! Thank you. 谢谢。

You probably want to pass in a "real" function (and not a value!). 您可能想要传递“实数”函数(而不是值!)。 Notice that you have to define a function or use a lambda expression here. 请注意,您必须在此处定义函数或使用lambda表达式。

r_sums(lambda x: np.sin(x**2+3),np.linspace(1,4,200),'left')

will work. 将工作。

The lambda expression is just a function taking one argument x and returning np.sin(x**2+3) lambda表达式只是一个带有一个参数x并返回np.sin(x**2+3)的函数

it would be the same as: 它与以下内容相同:

def function_sin_xsqaured_plus_3(x):
    return np.sin(x**2+3)

r_sums(function_sin_xsqaured_plus_3,np.linspace(1,4,200),'left')

(which also works) (也可以)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM