Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I iterate through a list and added them, It gave me a weird sum

a= [8, 12, 11, 15, 12, 2, 16, 3, 6, 19]
mean_a = sum(a)/len(a)
b = list(map(lambda x: x-mean_a, a))

tot = 0
for i in b:
    tot+=i
print(tot**2)

#it gave me this weird answer: 1.262177448353619e-29

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m assuming you’re expecting 0? If so, this is just another case of a floating-point precision error, as floating point numbers are processed by computers in base 2 fractions. The answer is effectively 0; you can round to a certain number of decimal places to get this answer.

sum(a) = 104
len(a) = 10
    
mean_a = 10.4

b = [-2.4000000000000004, 1.5999999999999996, 0.5999999999999996, 4.6, 1.5999999999999996, -8.4, 5.6, -7.4, -4.4, 8.6]

sum(b) = -3.552713678800501e-15

sum(b)**2 = 1.262177448353619e-29

The floating point error occurs twice; when you create b, and when you sum its values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading