user1412716 - 2 months ago 22

Python Question

I've been using the

`numpy.polyfit`

`import matplotlib.pyplot as plt`

from numpy import *

x=[1,2,3,4,5,6,7,8,9,10]

y=[100,85,72,66,52,48,39,33,29,32]

fit = polyfit(x, y, degree)

fitfunction = poly1d(z4)

to_predict=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

plt.plot(to_predict,fitfunction(to_predict))

plt.show()

After I run that, this shows up (I tried putting a picture up but stackoverflow won't let me).

I want to force it to go through zero.

How would I do that?

Answer

If you don't need the fit's error be computed using the original least square formula (i.e. minimizing ∑ |y_{i} - (ax_{i}^{2} + bx_{i})|^{2}), you could try to perform a *linear* fit of `y/x`

instead, because (ax^{2} + bx)/x = ax + b.

If you must use the same error metric, construct the coefficient matrices directly and use `numpy.linalg.lstsq`

:

```
coeff = numpy.transpose([x*x, x])
((a, b), _, _, _) = numpy.linalg.lstsq(coeff, y)
polynomial = numpy.poly1d([a, b, 0])
```

(Note that your provided data sequence does not look like a parabola having a y-intercept of 0.)