Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deal with overflow in exp using numpy

Using numpy, I have this definition of a function:

def powellBadlyScaled(X):     f1 = 10**4 * X[0] * X[1] - 1     f2 = numpy.exp(-numpy.float(X[0])) + numpy.exp(-numpy.float(X[1])) - 1.0001     return f1 + f2 

This function is evaluated a huge number of times on an optimization routine. It often raises exception:

RuntimeWarning: overflow encountered in exp 

I understand that operand cannot be stored in allocated space for a float. But how can I overcome the problem?

like image 528
kiriloff Avatar asked Mar 04 '12 22:03

kiriloff


People also ask

How can we prevent overflow encountered in exp?

Fix for Overflow in numpy. We have to store values in a data type capable of holding such large values to fix this issue. For example, np. float128 can hold way bigger numbers than float64 and float32 . All we have to do is just typecast each value of an array to a bigger data type and store it in a numpy array.

What does overflow encountered in exp mean?

This warning occurs when you use the NumPy exp function, but use a value that is too large for it to handle. It's important to note that this is simply a warning and that NumPy will still carry out the calculation you requested, but it provides the warning by default.

Does NumPy have exp?

The exp function in NumPy is used to compute the exponent of all values present in the given array. e refers to Euler's constant. It has an approximate value of 2.718.

What does NumPy exp return?

Return : An array with exponential of all elements of input array.


2 Answers

You can use the bigfloat package. It supports arbitrary precision floating point operations.

http://packages.python.org/bigfloat/

import bigfloat bigfloat.exp(5000,bigfloat.precision(100)) # -> BigFloat.exact('2.9676283840236670689662968052896e+2171', precision=100) 

Are you using a function optimization framework? They usually implement value boundaries (using penalty terms). Try that. Are the relevant values really that extreme? In optimization it's not uncommon to minimize log(f). (approximate log likelihood etc etc). Are you sure you want to optimize on that exp value and not log(exp(f)) == f. ?

Have a look at my answer to this question: logit and inverse logit functions for extreme values

Btw, if all you do is minimize powellBadlyScaled(x,y) then the minimum is at x -> + inf and y -> + inf, so no need for numerics.

like image 114
Johan Lundberg Avatar answered Oct 10 '22 13:10

Johan Lundberg


You can use numpy.seterr to control how numpy behaves in this circumstance: http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

You can also use the warnings module to control how warnings are or are not presented: http://docs.python.org/library/warnings.html

like image 44
Mike McKerns Avatar answered Oct 10 '22 12:10

Mike McKerns