Tuesday, December 24, 2024
Google search engine
HomeLanguagesCheck the equality of integer division and math.floor() of Regular division in...

Check the equality of integer division and math.floor() of Regular division in Python

For large quotients, floor division (//) doesn’t seem to be necessarily equal to the floor of regular division (math.floor(a/b))

Examples:

Input : 269792703866060742 // 3 
Output : 89930901288686914

Input : math.floor(269792703866060742 / 3)
Output : 89930901288686912

In the above examples, the output for floor division(//) is 89930901288686914 and the output for math.floor is 89930901288686912. All the digits are equal to each other except the last two digits in this example i.e 14 and 12.

The reason the quotients in the example is not equal is, in the math.floor(a/b) case the result is calculated with floating-point arithmetic (IEEE-754 64-bit), which means there is a maximum precision. The quotient obtained is larger than the 2^53 limit above which floating-point is no longer accurate up to the unit. However, with the floor division(//) Python uses its unlimited integer range, and so that result is correct.

Note: For int and long arguments, true division (/) may lose information; this is in the nature of true division (as long as rationals are not in the language). Algorithms that consciously use longs should consider using //, as true division (/) of longs retains no more than 53 bits of precision (on most platforms).

On a typical computer system, a ‘double precision’ (64-bit) binary floating-point number has a coefficient of 53 bits, an exponent of 11 bits, and one sign bit. Refer IEEE 754.

Example:




# Python program to demonstrate
# equality of integer division and 
# math.floor
  
  
import math
  
  
# First case: Take x smaller
# than 2 ^ 53 . 
x = 269
y = 3
if (x // y) == math.floor(x / y):
    print("Equal Output")
      
else:
    print("Not Equal Output")
  
      
# Second case: Take x larger
# than 2 ^ 53.
x = 269792703866060742
y = 3 
if (x // y) == math.floor(x / y):
    print("Equal Output")
      
else:
    print("Not Equal Output")


Output:

Equal Output
Not Equal Output

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments