[SciPy-User] curve_fit with float32 values

Georg Brandl g.brandl@gmx....
Sat Jan 12 06:54:10 CST 2013


Hi all,

while trying to show a colleague who hadn't done any Python before
how easy it is to load and fit some data, we had the problem that
curve_fit didn't appear to do any fitting at all.

In the end (which took quite a while!) we found that the problem
was that the X data (which was directly loaded from a HDF file)
had a float32 dtype.  This seems to confuse curve_fit.  Same goes
for float16.  float128 at least raises an exception.  Integer types
seem fine given rounding, see the code/output below.

If it's a big task to make curve_fit work with float32, then at least
a warning would be appreciated if the input types won't work.

cheers,
Georg

Test code below:

from numpy import sqrt, exp, pi, random, linspace, array
from scipy.optimize import curve_fit

def gauss(x, b, a, c, w):
        return b + a / sqrt(2*pi)*exp(-(x-c)**2/(2*w**2))

op    = array([1.0, 50.0, 88.0, 1.0])
print 'Original:     ', op
guess = array([0.0, 40.0, 90.0, 2.0])
print 'Guess:        ', guess

x0 = linspace(80, 100, 500)
y = gauss(x0, *op)

for dt in ['float64', 'float32', 'float16', 'int64', 'int32']:
    x = x0.astype(dt)
    p, c = curve_fit(gauss, x, y, guess)
    print 'Fit (%-7s):' % dt, p


***** Output:

Original:      [  1.  50.  88.   1.]
Guess:         [  0.  40.  90.   2.]
Fit (float64): [  1.  50.  88.  -1.]
Fit (float32): [  2.87328455e-07   4.00000000e+01   9.00000000e+01   2.00000000e+00]
Fit (float16): [  0.  40.  90.   2.]
Fit (int64  ): [  0.99921103  48.00234957  87.50399972   1.03986117]
Fit (int32  ): [  0.99921103  48.00234957  87.50399972   1.03986117]



More information about the SciPy-User mailing list