not exact result of sum in python 3

78 views Asked by At

I make functions of sum from 1 to last number as follows

def sum_way1(last_num):
    sum_val = 0
    for num in range(1, last_num+1):
        sum_val=sum_val+num
    return sum_val

def sum_way2(last_num):
    return int((last_num*(last_num+1))/2)

But the result as follows:

  • sum from 1 to 10000000000 : 50000000005000000000, execution time: 268.999 sec
  • sum from 1 to 10000000000 : 50000000005000003584, execution time: 0.000 sec

The result of sum_way2 function is not exact. Please let me know why I cannot get exact result of sum_way2 function?

Exact result:

  • sum from 1 to 10000000000 : 50000000005000000000, execution time: 268.999 sec
  • sum from 1 to 10000000000 : 50000000005000000000, execution time: 0.000 sec
1

There are 1 answers

2
k314159 On

The problem is caused by the fact that the / operator in Python always returns a float result, even when its operands are int. So what you are doing here is:

     last_num*(last_num+1))/2  -- this is a float, which has limited precision
int((last_num*(last_num+1))/2) -- now it's an int,
                                  but you can't add missing precision
                                  to what originally had limited precision

What you need to do is stay with ints throughout your calculation. Use the integer division operator // instead:

def sum_way2(last_num):
    return (last_num*(last_num+1)) // 2

(P.S. if you're looking at an old book or website, which uses Python 2, then its / operator did integer division if it had integer operands. That's no longer the case with Python 3.)