Chi square numpy.polyfit (numpy)

casper picture casper · Mar 29, 2011 · Viewed 9.7k times · Source

Could someone explain how to get Chi^2/doF using numpy.polyfit?

Answer

Sven Marnach picture Sven Marnach · Mar 30, 2011

Assume you have some data points

x = numpy.array([0.0, 1.0, 2.0, 3.0])
y = numpy.array([3.6, 1.3, 0.2, 0.9])

To fit a parabola to those points, use numpy.polyfit():

p = numpy.polyfit(x, y, 2)

To get the chi-squared value for this fit, evaluate the polynomial at the x values of your data points, subtract the y values, square and sum:

chi_squared = numpy.sum((numpy.polyval(p, x) - y) ** 2)

You can divide this number by the number of degrees of freedom if you like.