2

Here is a simple python snippet which generates 100 random numbers between 0 and 1, sum it, shuffle it, sum it and so on...

import random

rands=[]
for i in range(0,100):
    rands.append(random.uniform(0,1))

print(sum(rands))

random.shuffle(rands)
print(sum(rands))

random.shuffle(rands)
print(sum(rands))

random.shuffle(rands)
print(sum(rands))

When I run the code on python3 it generates different output in different print statement after shuffling the array. I understand that the way the floating point numbers are stored in memory, there will be some loss in the precision.

But when I run the code in python2, it returns the same output in every print statement.

Can someone help me understand why?

Gaurav Neema
  • 280
  • 3
  • 11
  • Python 2 prints less digits by default, so the value you see is heavily rounded, and you don't see the differences caused by the order of additions. – Thierry Lathuille May 01 '20 at 06:54

0 Answers0