Inconsistency in division of large numbers in python3

Viewed 126

When I calculated 24! using math library, the result is different compared to 24! calculated by dividing 25! by 25. Why is this?

>>> import math
>>> f=math.factorial(25)
>>> int(f/25)
620448401733239409999872
>>> math.factorial(24)
620448401733239439360000
>>> 
2 Answers

/ performs "true division". The result is a floating point number, which does not have enough precision to represent the exact quotient. Calling int cannot reverse the precision loss. The errors in floating point math & rounding are causing the discrepancy.

// is integer division - which is what you want:

>>> f = math.factorial(25)
>>> f/25
6.204484017332394e+23
>>> int(f/25)
620448401733239409999872
>>> math.factorial(24)
620448401733239439360000
>>> f//25
620448401733239439360000   # correct answer

you must not use / operation and int() after division. this code will round the exact division. but when you use factorial for 24 python is using * operations.

>>> from math import factorial
>>> f25 = factorial(25)
>>> f25
# 620448401733239439360000

here you can use // instead of / operation. see operations explanation here.

>>> f24 = factorial(24)
620448401733239439360000
>>> f25 // 25
620448401733239439360000
Related