Shekhar Karna
Shekhar Karna

Reputation: 13

Inconsistency in python division operation

I was performing simple division x = a/b, where a = 314159265389793240 and b=1. The answer x was completely unexpected. x came out to be 3.141592653897932e+17. This was really unexpected. Is there any way to do division in a consistent way? I am using python 3.8.5.

Upvotes: 0

Views: 94

Answers (1)

Amadan
Amadan

Reputation: 198446

In Python 3, / is floating-point division. Both of your operands get coerced to floating point, and you get a floating point result. The floating point format does not have enough precision to hold your number exactly, so some of the later digits get fudged. See Is floating point math broken? for more details.

Python 3 also has an integral division operator, //, which, if operands are integers, gives the result you expected.

print(314159265389793240 / 1)    # 3.141592653897932e+17
print(314159265389793240 // 1)   # 314159265389793240

Upvotes: 1

Related Questions