Reputation: 23256
Is there some way I could create a lambda function dynamically? For example,
f = lambda t : (1 + 32*t + 23*np.power(t,2) + 23*np.power(t,3) + 23*np.power(t,4))
in the above lambda function f
, I want to increment the value of t
in 23*np.power(t,2)
and want it to go until 467. So:
f = lambda t : (1 + 32*t + 23*np.power(t,2) + .. + 23*np.power(t,467))
Is there a way I could do this automatically?
Upvotes: 2
Views: 551
Reputation: 231385
The two parameters of np.power
broadcast against each other.
def foo(t, p):
return 1+32*t + np.sum(23*np.power(t,np.arange(*p)[:,None]), axis=0)
This is written to take a t
array, and a power range:
In [445]: foo(np.linspace(0,1,11),(2,4))
Out[445]:
array([ 1. , 4.453, 8.504, 13.291, 18.952, 25.625, 33.448, 42.559,
53.096, 65.197, 79. ])
In [446]: foo(np.linspace(0,1,11),(2,468))
Out[446]:
array([1.00000000e+00, 4.45555556e+00, 8.55000000e+00, 1.35571429e+01,
1.99333333e+01, 2.85000000e+01, 4.09000000e+01, 6.09666667e+01,
1.00200000e+02, 2.16100000e+02, 1.07510000e+04])
This version gives the caller more control:
def foo(t, p, axis=0):
return 1+32*t + np.sum(23*np.power(t,p), axis=axis)
e.g. a 2d t
array (but you have to understand broadcasting well):
In [449]: foo(np.linspace(0,1,10).reshape(2,5),np.arange(2,468)[:,None,None])
Out[449]:
array([[1.00000000e+00, 4.87500000e+00, 9.57142857e+00, 1.55000000e+01,
2.34000000e+01],
[3.47500000e+01, 5.30000000e+01, 8.85000000e+01, 1.93000000e+02,
1.07510000e+04]])
Upvotes: 2
Reputation: 8781
You might you something like f = lambda t : 1 + sum(23 * np.power(t, i) for i in range(1, 467))
. You can't use for loops or something like that, but simple expressions, function calls etc. you can
Upvotes: 4