Coding Python Programming

Benefits of Double Division Operator Over Single Division Operator in Python

The Double Division operator in Python returns the ground value for both integer and floating-point arguments after division.

# A Python program to demonstrate use of   
# "//" for both integers and floating points 
  
print(5//2) 
print(-5//2) 
print(5.0//2) 

Output:

2
-3
2.0

The single division operator behaves abnormally generally for very large numbers.

Example 1:

# single division 
print(1000000002/2) 
  
# Gives wrong output 
print(int(((10 ** 17) + 2)/2)) 
  
# Gives Correct output 
print(((10 ** 17) + 2)//2) 

Output:

500000001.0
50000000000000000
50000000000000001

Example 2:

x = 10000000000000000000006
if int(x / 2) == x // 2: 
    print("Hello") 
else: 
    print("World") 

Output:

World

The Output should be Hello if the only division operator behaved normally because 2 properly divides x. But the output is World because the results after Single Division Operator and Double Division Operator aren’t an equivalent.

This fact can be used for programs such as finding the sum of first n numbers for a large n.

n = 10000000000
  
s1 = int(n * (n + 1) / 2) 
s2 = n * (n + 1) // 2
  
print("Sum using single division operator : ", s1) 
print("Sum using double division operator : ", s2) 

Output:

um using single division operator :  50000000005000003584
Sum using double division operator :  50000000005000000000

Thus, the result found by using the only division operator is Wrong, while the result found by using the double division operator is Correct. this is often an enormous advantage of Double Division Operator Over Single Division Operator in Python.

READ  Java Algorithm - Introduction to Stack
X