[Python] scipy curve_fit gives wrong results for float32 input

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    In the very simple example below (fitting a straight line y=ax+b with known outcome `a=b=0), the SciPy curve_fit function yields a wrong result when the x-variable is supplied as float32-type:

    import numpy as np
    import scipy.optimize as opt

    def func(x, a, b): return a*x + b

    x = np.array([0,1])
    y = np.array([0,0])
    p0 = [0.1, 0.1]
    p1 = opt.curve_fit(func, x , y, p0=p0)
    p2 = opt.curve_fit(func, np.float64(x), y, p0=p0)
    p3 = opt.curve_fit(func, np.float32(x), y, p0=p0)

    print '\n p1 = ',p1,'\n p2 = ',p2,'\n p3 = ',p3


    which yields the output:

    p1 = (array([ 0., 0.]), inf)
    p2 = (array([ 0., 0.]), inf)
    p3 = (array([ 0.1, 0.1]), inf)


    Why is that last result (obtained with float32-input) different from the other two, and - obviously - wrong? Apparently, curve_fit has not performed even a single iteration, since the fit result p3 equals the initial guess p0. To me, this seems like a bug ...

    Continue reading...

Compartilhe esta Página