0

I am not sure why I am getting two different results in Python when I sum an array sorted in ascending and descending fashion. Descending gives me the exact number.

    def alg_sum(x):  # x == x[:n]
    s = 0.
    for x_i in x:  # x_0, x_1, \ldots, x_{n-1}
        s += x_i
    return s

N_1 = [0.3 + 0.2 + 0.1]
N_2 = [0.1 + 0.2 + 0.3]
print("N_1:", alg_sum(N_1))
print("N_2:", alg_sum(N_2))
N_1: 0.6
N_2: 0.6000000000000001
Adaptron
  • 11
  • 4
  • @NielGodfreyPonciano Not really. I understanding the rounding with floating points but why is it accurate when it is descending? – Adaptron Sep 20 '21 at 02:53
  • Neither result is exact. It's just rounding differently. None of the values you're adding, nor their sum, are exactly representable as floating point values. – Tom Karzes Sep 20 '21 at 02:57

0 Answers0