2

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?

2
  • q+32*t+sum(23 * np.power(t,x) for x in range(2,468))? its either goign to be an insanely high number or 0? mabye something sensible for t<0 - what good is it for?# Commented May 26, 2019 at 12:12
  • @PatrickArtner Will be a small number. I need to solve a polynomial equation that goes to inf Commented May 26, 2019 at 12:28

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

There is a syntax error in your code SyntaxError: unexpected EOF while parsing
End range should be 468.
2

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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.