[SciPy-user] linear (polynomial) fit with error bars

Robert Kern robert.kern@gmail....
Thu Apr 10 15:08:49 CDT 2008

On Thu, Apr 10, 2008 at 7:09 AM, massimo sandal <massimo.sandal@unibo.it> wrote:

>  massimo@calliope:~/Python/linfit$ python linfit.py
>  Traceback (most recent call last):
>    File "linfit.py", line 31, in <module>
>      w, success = optimize.leastsq(errfunc, [0,0], args=(xval,yval),
>  diag=weigths)
>    File "/usr/lib/python2.5/site-packages/scipy/optimize/minpack.py",
>  line 262, in leastsq
>      m = check_func(func,x0,args,n)[0]
>    File "/usr/lib/python2.5/site-packages/scipy/optimize/minpack.py",
>  line 12, in check_func
>      res = atleast_1d(apply(thefunc,args))
>    File "linfit.py", line 4, in errfunc
>      return Y-(a[0]*X+a[1])
>  ValueError: shape mismatch: objects cannot be broadcast to a single shape
>  which baffles me. What should I look for to understand what I am doing
>  wrong?

Print out the various individual parts of that expression to make sure
they are compatible (or use a debugger to do the same interactively).

  print Y
  print X
  print a

In this case, the problem is that you are passing in X and Y as lists
instead of arrays. Since a[0] is a numpy scalar type that inherits
from the builtin int type, a[0]*X uses the list type's multiplication
which leaves you with an empty list.

Instead of constructing xval and yval as lists, use numpy.empty().


Also, you don't need to "declare" the variables "w" and "success".

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco

More information about the SciPy-user mailing list