2
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

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 2
    What is weird about this? What is the expected result? – illuminator3 Apr 23 '22 at 22:17
  • I was just wondering why I didn't get a zero instead. – Keith Nohby Caitor Apr 23 '22 at 22:39
  • you essentially compute the mean of your values, then you deduct that mean from every value and sum it up. Theoretically this should evaluate to 0 - floating math has limited precision - your errors accrue and then you square this (very small) error to get an even smaller one. – Patrick Artner Apr 23 '22 at 22:44

1 Answers1

2

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.

Guy Keogh
  • 549
  • 2
  • 5
  • 15