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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With