In Python, while dividing bigger values I am getting inaccurate output, for example:-
(1227073724601519345/101)
= 12149244798034845. But in Python it becomes
(1227073724601519345/101)
= 1.2149244798034844e+16 which converted to int is 12149244798034844.
As you can see
( correct_output - approx_output ) = 1
Is there any way I can avoid this? There is no such inaccuracy while multiplying even bigger numbers, for example:-
(123468274768408415066917747313280346049^2) - (56 * (16499142225694642619627981620326144780^2))
= 1
which is accurate.
Computer commonly use IEEE 754 Standard for Floating-Point Arithmetic. That means that floating point numbers have a limited precision of 53 bits (about 15 or 16 decimal digits).
As you have used (x / y)
Python has given you a floating point result, and has the result would require more than 15 decimal digit it cannot be accurate.
But Python also have an integer division operator (//
). Integers in Python 3 are multi-precision numbers, meaning that they can represent arbitrary large integers (limited only by the available memory...). It is the reason why you have accurate result when multiplying large numbers. So to get the exact integer result, you should use this:
1227073724601519345//101
which gives as expected 12149244798034845