I want to take the elements of List3
which describes the amount of production Days available at each month of the year, and weight this together with the annual production in List1
to accomplish a monthly production volume. My code is:
List3 = [31,28,31,30,31,30,31,31,19,31,30,31]
List = [5150]
for i in xrange(len(List3)):
j = List3[i]
g = g+j
for i in xrange(len(List)):
a = List[i]/g
for j in xrange(len(List3)):
print (a*List3[j])
where a
describes how much production is made each day, so multiplying this with the elements of List3[j]
for each month ought to provide the total monthly production.
However, running this program yields the monthly production:
434 392 434 420 434 420 434 434 266 434 420 434
which sums to 4956. But the annual production in List3
was 5150 units. Hence, there is a discrepancy of 154 units between the annual production and the sum of the monthly production.
Can somebody see where I have done wrong? I remember that I have remade this code earlier to become that the sum of the monthly production at most differed approximately 10 units from the annual production, which would suffice. I don't remember how I did however.
Regards,
It's caused by rounding. In Python 2, this line is integer division:
a = List[i]/g
Here's a simple experimental workflow with the interactive interpreter to illustrate the issue:
>>> l3 = [31,28,31,30,31,30,31,31,19,31,30,31]
>>> l = [5150]
>>> g = sum(l3)
>>> g
354
>>> a = l[0] / g
>>> a
14
>>> sum(a*e for e in l3)
4956
>>> a = l[0] / float(g)
>>> a
14.548022598870057
>>> sum(a*e for e in l3)
5149.999999999999