0
    n = int(input())
    sum1 = (n * (n + 1)) / 2
    sum2 = int(sum1)
    sum2 = sum2 + 100
    sum1 = sum1 + 100
    if sum2 == sum:
        print("same")
    elif sum2 > sum1:
        print("less")
    elif sum2 < sum1:
        print("more")
    print("sum1=",sum1)
    print("sum2=",sum2)

INPUT:n=10000000000(or anything greater than 10^9)
OUTPUT:less
sum1= 5.0000000005e+19
sum2= 50000000005000003684

Both sum1 and sum2 should be equal but somehow i lose precision when exponentials come into play and if i tried to print the difference between sum1 and sum2 , i get zero(0.0) as output.For smaller values of n , i get accurate answers.

So, How do i avoid losing precision and get exact results when i add really large integers and smaller integres?
Note: This code is just a part of a larger program, so please keep your answers general.Thank you.

  • 1
    Yes, this is an inherent limitation of floating point numbers. You can never get exact results using floating point numbers. – juanpa.arrivillaga Sep 10 '20 at 15:35
  • 1
    Keep everything as integers and you will be fine -- they are arbitrary precision in Python. If `n` is an integer then `n * (n+1)` must be divisible by 2, so instead of `n * (n+1) / 2`, use integer division i.e. `n * (n+1) // 2` and you will get an integer with the value that the floating-point value *would* have if it had sufficient precision. The problem you are getting is *not* adding larger and smaller integers as the question claims, but it is with adding *floats* after you have created them using the `/` division operator. – alani Sep 10 '20 at 15:38
  • For more information on the problems with `float` types see [Is floating point math broken?](https://stackoverflow.com/q/588004/5987) – Mark Ransom Sep 10 '20 at 16:07

1 Answers1

1

As alani points out, there is an implicit conversion to float in sum1 = (n * (n + 1)) / 2. E.g. isinstance(1/1, float) == True. Use integer division //. n*(n+1) is always even so you will never have an N.5 result where you lose accuracy. Also, the repr of floats is always either with a decimal point (1.0) or an exponent (1e+20) or both, so if you ever see that, you know you have floats.

jpkotta
  • 9,237
  • 3
  • 29
  • 34