Reputation: 432
I want to generate a polynomial equation by giving values and get an equaiton. However when I control it with given x values I get different values from equation here is my code and outputs:
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
It gives me this equation: -0.001416*x^2 + 0.1504*x + 1.72
OUTPUTS
x expected(y) returned(y)
1 1 1.868984
2 4 2.015136
3 1 2.158456
9 3 2.9589040000000004
Am I wrong or I read them wrong?
Upvotes: 1
Views: 3033
Reputation: 953
You seem to misunderstand the concept of polynomial fitting. When you call polyfit(x, y, n)
, what it does is give you the n-th (or lesser) degree polynomial that best fits the set of points (x, y). So by calling the polyfit with n = 2
, it returns you the best quadratic polynomial that fits the points you've given it. This polynomial is only an approximation to your set, so it is expected for the return values to be different from the expected values, worsened by the fact that they are poorly represented by a quadratic polynomial.
The following code visually demonstrates how this is true. Change your points, the n
value for the polyfit()
function and see if you can better grasp the concept:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
x_fit = np.linspace(-100, 100, 1000)
y_fit = [f(_x) for _x in x_fit]
plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()
Upvotes: 2