0
votes

I have the following bit of matlab code:

f=@(h)(exp(-2*mun*(h/sigma+1.166))-1+2*mun*(h/sigma+1.166))/(2*mun^2)-ARL0;

The parameters aren't important, they are all just constants at this point. What is important is that now I can evaluate that function for any value of h just by calling f(h). In particular, I can find the zeros, min, max, etc of the function over any interval I specify.

I am translating this code into python, mostly as an exercise in learning python, and I was wondering if there is anything similar (perhaps in numpy) that I could use, instead of setting up a numpy array with an arbitrary set of h values to process over.

I could do something like (pseudocode):

f = numpy.array(that function for h in numpy.arange(hmin, hmax,hstep))

But this commits me to a step size. Is there any way to avoid that and get the full precision like in matlab?

EDIT: what I actually want at the end of the day is to find the zeroes, max, and min locations (not values) of the function f. It looks like scipy might have some functions that are more useful here: http://docs.scipy.org/doc/scipy/reference/optimize.html

2

2 Answers

1
votes

If you are just looking for the f values for integer values of x, the following will work:

f = [your_function(x) for x in xrange(hmin, hmax)]

If you want finer granularity than integer values, you can do:

f = [your_function(x) for x in xrange(hmin, hmax, hstep)]

If you want exact solutions to the zeroes, max, and min locations, I agree with your edit: use scipy optimize.

Two important notes about the scipy optimize functions:

  1. It seems you want to use the bounded versions
  2. There is no guarantee that you will find the actual min/max with these functions. They are non-deterministic optimization functions that can fall victim to local minimums/maximums. If you want to evaluate the mins/maxs symbolically, I suggest looking into sage
1
votes

The Python equivalent of function handles in MATLAB (the @ notation) are called "lambda functions" in python. The equivalent syntax is like so:

Matlab:

func = @(h)(h+2):

Python:

func = lambda h: h+2

For your specific case, you would implement the equivalent of the matlab function like this:

import numpy as np
f = lambda h: (np.exp(-2*mun*(h/sigma+1.166))-1+2*mun*(h/sigma+1.166))/(2*mun**2)-ARL0

f can then be used as a function and applied directly to any numpy array. So this would work, for example:

rarr = np.random.random((100, 20))
frarr = f(rarr)