1

I have a function which looks like this:

def test(x,q0):
    q = q0/(1+x**2)
    h_func = lambda t: 1/sp.cosh(t)**2
    fun = lambda t: sp.log(1+q*h_func(t))
    return spi.quad(fun,-sp.inf,sp.inf)[0]

How do I make it vectorized so that it can accept x as an array? Right now, it shows

TypeError: only length-1 arrays can be converted to Python scalars

I can achieve this in Matlab using

integral(fun,-Inf,Inf,'ArrayValued',true),

but is there a Python equivalent of the 'ArrayValued',true in Matlab?

Physicist
  • 2,848
  • 8
  • 33
  • 62
  • What's the expected output? Say, if you called it with `test(np.array([1, 2, 3]), 0.1)` what should be the result? – MB-F Dec 21 '17 at 09:07
  • it should give `array([ 0.0983764 , 0.03973614, 0.01993369])`, which is just what we get if we apply the function to each of the element in `np.array([1,2,3])` separately. – Physicist Dec 21 '17 at 09:36
  • The quick and dirty solution would be to do `test = np.vectorize(test)` but note that `vectorize` is not a performance feature :) – MB-F Dec 21 '17 at 09:39
  • Is there a specific reason why you don't just want to iterate through `x` within `test`? I doubt that it would be much slower than calling a function that does the iteration for you (if such a function would exist). – Thomas Kühn Dec 21 '17 at 09:46
  • I want to do some data fitting with a function that looks similar to the one in example, and it seems that `sp.optimize.curve_fit` requires a function which accepts vector `z`, so I want the function to be vectorizable. I can add a for loop inside the function, but it seems to me that this is quite slow, especially when it is evaluated many times during the optimization. I can think of pre-evaluating the function over a 2d array for various `t` and `z`, and do the numerical integration myself using `trapz` or `simps` , but I wonder if a better method exists. – Physicist Dec 21 '17 at 09:53
  • Possible duplicate of [NumPy vectorization with integration](https://stackoverflow.com/questions/41223186/numpy-vectorization-with-integration) –  Dec 21 '17 at 16:21

0 Answers0