+ 6
#why these are not equal print( 1000 // 1.6 ) print ( 1000 / 1.6 )
8 odpowiedzi
+ 5
Bob_Li
I think it is because of the floating point system makes 1000 // 1.6 return 624.0
By running 1000 % 1.6, we get 1.59...446, a number very close to 1.6
from decimal import *
print(Decimal(str(1000)) // Decimal(str(1.6)))
# Decimal('625')
[Edit]
Code in action
https://code.sololearn.com/cjYGiHAq0fpQ/?ref=app
+ 3
Solo , I was also going to say the same, but integer division with a float returns a float.
and I cannot explain why it becomes 624.0 ??
That's why I deleted my first reply. The documentation says that 1000//1.6 should be the same as math.floor(1000/1.6) but that should give 625 not 624.0. And it can return a float type, so maybe integer division is a misnomer.
https://code.sololearn.com/cpz3DkDtgrbz/?ref=app
+ 3
Bob_Li
Not quite so, the integer division operator discards the fractional part and outputs the integer part, but in python this does not mean that it outputs the value type as an integer, as you can see python can work with fractional numbers, the difference is only in the output of the value type. Although in reality integer division, like modulo division, cannot be used with fractional numbers...😎
And to explain the result , I would do this:
Let's divide in column 10 by 1.6 as we were taught at school.
For the convenience of division, multiply both parts of the expression by 10, we get: 100÷16=?
100 | 16
- –––
96 | 6.25
====
40
-
32
===
80
-
80
===
0
Thus we get that
at 10÷1.6 we lose 0.25,
at 100÷1.6 we lose 0.5, well,
at 1000÷1.6 we lose respectively 1 with integer division.
As a result, instead of 625 we get 624...😎
+ 2
Wong Hei Ming interesting...
but that seems to introduce non-intuitive results.
so 1000//1.6 is being interpreted as someting like
print(math.floor(1000/1.600000000000001))
which gives 624.
and that should be interpreted as an erroneous result, since the data was altered.
I still feel that one should not use floats in integer division to avoid surprises like these...
+ 2
modulo and rounding rules are also implemented differently by different languages, so there's that extra discrepancy. And I agree, floating points and (negative numbers) gets tricky to implement and should be avoided, or at least used with caution, when operations require the use of these operations.
floating points... the mother of inaccuracies...😅
+ 2
Bob_Li , absolutely right, do not forget that we are dealing with hardware that stores all information in binary code and the programmer had the task to adapt it as much as possible to the general laws of mathematics ...😎
+ 1
Because in the first case, an integer division operation occurs.
0
It's very simple. Different symbols, different answers. `//` removes decimals, ` / ` keeps decimals.