I am wondering if there is any way of adding to lambda functions at the function level.
我想知道是否有任何方法在函数级别添加lambda函数。
import numpy as np
f = lambda x: np.sin(5*x)+3
g = lambda x: np.cos(3*x)**2+1
x = np.linspace(-3.14,3.14,1000)
h = f+g % is there any way to create this ?
h_of_x = h(x)
This would be very helpful.
这将非常有帮助。
3 个解决方案
#1
May be this
可能是这个
h = lambda x: f(x)+g(x)
#2
If you're looking for symbolic mathematics, use sympy.
如果您正在寻找符号数学,请使用sympy。
from sympy import *
x = symbols("x")
f = sin(5*x)+3
g = cos(3*x)**2+1
h = f + g
#3
You can create a function plus
that takes two functions as input and return their sum:
您可以创建一个函数plus,它将两个函数作为输入并返回它们的总和:
def plus(f, g):
def h(x):
return f(x) + g(x)
return h
h = plus(lambda x: x * x, lambda x: x ** 3)
Example:
>>> h(2)
12
Defining plus
can have advantages, like:
定义加号可以带来优势,例如:
>>> f = lambda x: x * 2
>>> h = reduce(plus, [f, f, f, f]) # or h = reduce(plus, [f] * 4)
>>> h(2)
16
#1
May be this
可能是这个
h = lambda x: f(x)+g(x)
#2
If you're looking for symbolic mathematics, use sympy.
如果您正在寻找符号数学,请使用sympy。
from sympy import *
x = symbols("x")
f = sin(5*x)+3
g = cos(3*x)**2+1
h = f + g
#3
You can create a function plus
that takes two functions as input and return their sum:
您可以创建一个函数plus,它将两个函数作为输入并返回它们的总和:
def plus(f, g):
def h(x):
return f(x) + g(x)
return h
h = plus(lambda x: x * x, lambda x: x ** 3)
Example:
>>> h(2)
12
Defining plus
can have advantages, like:
定义加号可以带来优势,例如:
>>> f = lambda x: x * 2
>>> h = reduce(plus, [f, f, f, f]) # or h = reduce(plus, [f] * 4)
>>> h(2)
16