[SciPy-user] fsolve passing array not float

David M. Cooke cookedm at physics.mcmaster.ca
Tue May 16 16:09:28 EDT 2006


Mark Alford <alford at wuphys.wustl.edu> writes:

> I have a function of one floating-point variable, written in
> python. It has a root, and I want to use fsolve to find it. But fsolve
> passes an array (of length 1!) instead of a simple float.   What do I do?
> I want the function call to be efficient, because it will be repeated
> many times. And the function uses 'if(...)' tests on its argument
> so it is not easy to vectorize it.
>
> (a) Ideally I would like to tell fsolve not to pass silly length-1 arrays
>      to my function. But I expect that's not possible.
>
> (b) I could modify my function to test for a length-1 array, and pull out
>      the single element in that case. This feels wasteful (undoing fsolve's
>      work), but perhaps it can be done in an efficient way?
>
> (c) I could write a wrapper that takes an array as argument, and
>      calls my function many times to create an array of results.
>      How does one do this in an efficient way?

fsolve is designed to find the roots of a set of non-linear equations,
hence the array (of length #-of-variables). You could use one of the
1-d routines instead (brentq, for instance), which may be better for
your case, or use a wrapper. Assuming your function is func(x), this
would work:

def func_wrapper(x):
    return func(x[0])

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca




More information about the SciPy-User mailing list