user1412716 user1412716 - 1 year ago 231
Python Question

How to force polyfit with second degree to a y-intercept of 0

I've been using the

function to do some forecasting. If I put in a degree of 1, it works, but I need to do a second degree polynomial fit. In some cases it works, in other cases the plot of the prediction goes down and then goes up forever. For example:

import matplotlib.pyplot as plt
from numpy import *

fit = polyfit(x, y, degree)
fitfunction = poly1d(z4)


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 Source

If you don't need the fit's error be computed using the original least square formula (i.e. minimizing ∑ |yi - (axi2 + bxi)|2), you could try to perform a linear fit of y/x instead, because (ax2 + 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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download