GordonJun
GordonJun

Reputation: 35

Why is the calculation from my code giving me different answers from calculators?

I am using Python 3.6.0. I noticed that the output from my code and giving answers different from calculators and I could not find out why.

L = [5,5,2,3,4,5]

for i in range(len(L)):
    L[i] *= 1000

for i in range(len(L)):
    if i == 0:
        L[i] = int(L[i]*0.6+L[i+1]*0.2)

    if i < (len(L)-1) and i != 0:
        L[i] = int(L[i-1]*0.2+L[i]*0.6+L[i+1]*0.2)

print(L)

The output of the code is:

[4000, 4200, 2640, 3128, 4025, 5000]

However, there seems to be calculation problem when i is above 0. For example:

When i is 2, L[2] = int(L[1]*0.2+L[2]*0.6+L[3]*0.2) = 2800

but the output from the program is 2640. Where is the source of error?

I would greatly appreciate if anybody can assist me with this.

Upvotes: 0

Views: 209

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

I think the problem is that you're altering the array as you go through. That is, you're trying to calculate a new list from the old one - but because you're referring to values that you've already changed, it's interfering with the calculation.

If this is the issue, the fix is simple - just make a new list, say M, and replace L by Min everything but the formulas on the right-hand-side of the = signs.

Upvotes: 2

Related Questions