About half an hour thinking "what am i doing wrong!?" on the 5-lines code.. because Python3 is somehow rounding big integers. Anyone know why there is a problem such:
Python2:
int(6366805760909027985741435139224001 # This is 7**40.
/ 7) == 909543680129861140820205019889143 # 7**39
Python3:
int(6366805760909027985741435139224001
/ 7) == 909543680129861204865300750663680 # I have no idea what this is.
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, 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.
In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or 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.
Python 3 is not "rounding big integers". What it does is that it will return a float after division. Hence, in Python 2:
>>> 4/2
2
while in Python 3:
>>> 4/2
2.0
The reason for this is simple. In Python 2, /
being integer division when you use integers have some surprising results:
>>> 5/2
2
Ooops. In Python 3 this is fixed:
>>> 5/2
2.5
This means that in Python 3, your division returns a float:
>>> 6366805760909027985741435139224001/7
9.095436801298612e+32
This float has less accuracy than the digits you need.
You then convert this to an integer with int()
, and you get a number you don't expect.
You should instead use integer division (in both Python 2 and Python 3):
>>> 6366805760909027985741435139224001//7
909543680129861140820205019889143L
(The trailing L means it's a long integer, in Python 3 the long and the normal integer is merged, so there is no trailing L).
In Python 3 /
is floating point division so it may not treat your arguments like integers. Use
//
to do integer division in Python 3.
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