Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange division results in python 3

I think there is some inconsistency in the division operation, but I am not sure.

In the following code I would expect either a//c to be 100.0, or b//c to be -99.0.

a = 1.0
b = -1.0
c = 0.01

print (a/c)
print (a//c)
print (b/c)
print (b//c)

gives:

100.0
99.0
-100.0
-100.0

Thanks

like image 740
Baba Avatar asked Jun 14 '15 15:06

Baba


People also ask

How do you divide in Python 3?

In Python 3. x, slash operator ("/") does true division for all types including integers, and therefore, e.g. 3/2==1.5. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.

What is the result of floor division in Python?

In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number, making it equivalent to the math. floor() function.

How do you show division in Python?

In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

Does Python truncate division?

The truncating division operator (also known as floor division) truncates the result to an integer and works with both integers and floating-point numbers. As of this writing, the true division operator (/) also truncates the result to an integer if the operands are integers. Therefore, 7/4 is 1, not 1.75.


1 Answers

This is due to the way floating point numbers are represented. It's not true that 1.0 is exactly 100 times 0.01 (as far as floating points are represented internally). The operator // performs division and floors the result so it may be that internally the number is slightly less than 100.0 and this leads it to being floored to 99.0.

Furthermore, Python 3.x uses a different approach to showing you the floating point number as compared to Python 2.x. This means the result of 1.0 / 0.01, although internally slightly less than 100.0, will be displayed to you as 100.0 because the algorithm determined that the number is close enough to 100.0 to be considered equal to 100.0. This is why 1.0 / 0.01 is shown to you as 100.0 even though this may not be represented internally as exactly that number.

like image 130
Simeon Visser Avatar answered Jan 03 '23 14:01

Simeon Visser