2

Is there any other way than using a lambda function to integrate a function in python 2.7 over, say, the 2nd of two variables? For instance, I would like to integrate this example function over x:

import numpy as np
from scipy.integrate import quad

def sqrfn(a,x):
    return a*np.square(x)

This is easily achieved by:

quad(lambda x: sqrfn(2,x),0,10)

I'm wondering if there is another way to do this, for instance by using something similar to, which I think is much more intuitive:

quad(sqrfn,0,10,args(a=2))

Anyone got an alternative solution? (Yea, I could define the function as sqrfn(x,a) and use quad(sqrfn,0,10,args(2,)) instead, but that's not the point).

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Forzaa
  • 1,465
  • 4
  • 15
  • 27

2 Answers2

1

You could use functools.partial() for this:

In [10]: f = functools.partial(sqrfn, 2)

This makes f(x) equivalent to sqrfn(2, x):

In [11]: map(f, range(5))
Out[11]: [0, 2, 8, 18, 32]

Your example would then become:

quad(functools.partial(sqrfn, 2), 0, 10)
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • What would happen with this method if I had an n variable function and I would want to fix all but the k'th variable? – Forzaa Feb 15 '13 at 14:19
0
import functools
quad(functools.partial(sqrfn, 2), 0, 10)
Loren Abrams
  • 1,002
  • 8
  • 9