Reputation: 61
My water density calculation has a 4th order polynomial equation in it. I use a loop to solve the polynomial. I get the correct solution with a while loop; unfortunately, I don't understand for-in loop syntax well enough to make that work instead:
# Density of water in kg/m^3 wrt temperature (degC) at 1 atmosphere
def densityWater(tDegC):
#set up the counter, m
m = 0
#set up the data file (linear polynomial equation coefficients)
#polynomial is of the form ex^4 + dx^3 + cx^2 + bx + a (x = tDegC)
coeffWaterDensity = (-1.258606246688818E-07, 4.038794321262406E-05, -7.424005247974371E-03, 4.881970120567554E-02, 9.998909544205623E+02)
densityH2O = 0
while m < len(coeffWaterDensity):
densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
m = m + 1
return densityH2O
tDegC = input("At what temperature is the water you need the density for? Reply in celsius: ") tDegC = float(tDegC)
print("The density of water at "+ str(tDegC) + " celsius is " + "{:,.1f}".format(densityWater(tDegC)) + " kg/m^3")
But when I tried this for-in instead of the while loop, the result was incorrect
for m in range(len(coeffWaterDensity)):
densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
m = m + 1
return densityH2O
What is the most efficient and correct way to handle this?
Upvotes: 0
Views: 45
Reputation: 4323
You return
result of function inside loop.
And don't need to increment m
because for m in range(...)
do it for you.
for m in range(len(coeffWaterDensity)):
densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
return densityH2O
Upvotes: 2