Reputation: 1127
I fit a polynomial to points from list data
using the polyfit()
function:
import numpy as np
data = [1,4,5,7,8,11,14,15,16,19]
x = np.arange(0,len(data))
y = np.array(data)
z = np.polyfit(x,y,2)
print (z)
print ("{0}x^2 + {1}x + {2}".format(*z))
Output:
[0.00378788 1.90530303 1.31818182]
0.003787878787878751x^2 + 1.9053030303030298x + 1.3181818181818175
How to get a fit to points, with rounded coefficients for example to three decimal places? For example, to get:
[0.004 1.905 1.318]
0.004x^2 + 1.905x + 1.318
Upvotes: 1
Views: 1610
Reputation: 7994
There is no option in the polyfit
method for the purpose of rounding. IIUC, you can use round
after applying polyfit
.
import numpy as np
data = [1,4,5,7,8,11,14,15,16,19]
x = np.arange(0,len(data))
y = np.array(data)
z = np.polyfit(x,y,2).round(decimals=3)
array([0.004, 1.905, 1.318])
For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [R9] and errors introduced when scaling by powers of ten. -- Cited from numpy.around
Upvotes: 2