I’m trying to fit a curve to some data. When I evaluate the polynomial equation with one value, I get an expected float answer. When I evaluate the polynomial equation over an array, the for loop yields integer values when the intended result is floats.
I think I’m close, but I’m not sure what I’m doing wrong. Please advise.
JavaScript
x
14
14
1
from numpy.polynomial import polynomial as P
2
3
a = np.array([5, 55, 211, 250, 270, 300, 330, 350, 400, 450, 500, 550, 600, 750, 870, 1000])
4
b = np.array([0.38, 0.96, 1.90, 2.05, 2.13, 2.25, 2.35, 2.42, 2.60, 2.75, 2.90, 3.04, 3.18, 3.65, 4.06, 4.35])
5
6
c = P.polyfit(a, b, 2)
7
8
a_new = np.arange(2000)
9
b_new = np.arange(len(a_new))
10
11
for x in a_new:
12
b_new[x] = c[0] + c[1] * a_new[x] + c[2] * a_new[x]**2
13
print(str(x) + ', ' + str(b_new[x]))
14
Advertisement
Answer
Just issues with your b_new
change like this,
JavaScript
1
14
14
1
from numpy.polynomial import polynomial as P
2
3
a = np.array([5, 55, 211, 250, 270, 300, 330, 350, 400, 450, 500, 550, 600, 750, 870, 1000])
4
b = np.array([0.38, 0.96, 1.90, 2.05, 2.13, 2.25, 2.35, 2.42, 2.60, 2.75, 2.90, 3.04, 3.18, 3.65, 4.06, 4.35])
5
6
c = P.polyfit(a, b, 2)
7
8
a_new = np.arange(2000)
9
b_new = []
10
11
for x in a_new:
12
value = c[0] + c[1] * a_new[x] + c[2] * a_new[x]**2
13
b_new.append(value)
14