Home > OS >  How to Yeld Floats in a For Loop
How to Yeld Floats in a For Loop

Time:10-02

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.

from numpy.polynomial import polynomial as P

a = np.array([5, 55, 211, 250, 270, 300, 330, 350, 400, 450, 500, 550, 600, 750, 870, 1000])
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]) 

c = P.polyfit(a, b, 2)

a_new = np.arange(2000) 
b_new = np.arange(len(a_new))

for x in a_new:
    b_new[x] = c[0]   c[1] * a_new[x]   c[2] * a_new[x]**2
    print(str(x)   ', '   str(b_new[x]))

CodePudding user response:

b_new is an array of integers, b_new[x] = ... converts to an integer when assigning. Still, better to do:

P = np.polynomial.Polynomial.fit(a, b, 2)
a_new = np.arange(2000)
b_new = P(a_new)

CodePudding user response:

Just issues with your b_new change like this,

from numpy.polynomial import polynomial as P

a = np.array([5, 55, 211, 250, 270, 300, 330, 350, 400, 450, 500, 550, 600, 750, 870, 1000])
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]) 

c = P.polyfit(a, b, 2)

a_new = np.arange(2000) 
b_new = []

for x in a_new:
    value = c[0]   c[1] * a_new[x]   c[2] * a_new[x]**2
    b_new.append(value)
  • Related