why python int() works like this? [duplicate] - python

This question already has answers here:
Negative integer division surprising result
(5 answers)
Closed 8 years ago.
Just randomly tried out this:
>>> int(-1/2)
-1
>>> int(-0.5)
0
why the results are different??

Try this:
>>> -1/2
-1
>>> -0.5
-0.5
The difference is that integer division (the former) results in an integer in some versions of Python, instead of a float like the second number is. You're using int on two different numbers, so you'll get different results. If you specify floats first, you'll see the difference disappear.
>>> -1.0/2.0
-0.5
>>> int(-1.0/2.0)
0
>>> int(-0.5)
0

The difference you see is due to how rounding works in Python. The int() function truncates to zero, as noted in the docs:
If x is floating point, the conversion truncates towards zero.
On the other hand, when both operands are integers, the / acts as though a mathematical floor operation was applied:
Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.
So, in your first case, -1 / 2 results, theoretically, in -0.5, but because both operands are ints, Python essentially floors the result, which makes it -1. int(-1) is -1, of course. In your second example, int is applied directly to -0.5, a float, and so int truncates towards 0, resulting in 0.
(This is true of Python 2.x, which I suspect you are using.)

This is a result of two things:
Python 2.x does integer division when you divide two integers;
Python uses "Floored" division for negative numbers.
Negative integer division surprising result
http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html
Force at least one number to float, and the results will no longer surprise you.
assert int(-1.0/2) == 0
As others have noted, in Python 3.x the default for division of integers is to promote the result to float if there would be a nonzero remainder from the division.

As TheSoundDefense mentioned, it depends upon the version. In Python 3.3.2:
>>> int(-1/2)
0
>>> int(-0.5)
0

int() command truncates towards 0, unlike floor() which rounds downwards to the next integer.
So int(-0.5) is clearly 0.
As for -1/2, actually -1/2 is equal to -1! Therefore rounding downwards to the next integer is -1. In Python 2, -a/b != -(a/b). Actually, -1/2 equals floor(-1.0 / 2.0), which is -1.

Related

Python exponential calculation on fraction [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
I'm trying to calculate 27^(1/3) = 3. But it turns out not as expected.
>>> 27 ** (1/3)
1
>>> 27 ** (1/3.)
3.0
Firstly, why the first calculation will result in 1, is it because 1/3 is casted to an int so it equals zero?
Secondly, what does the '.' means in Python in general, could I append a dot to any number in order to cast it from int to double?
Thanks.
Firstly, why the first calculation will result in 1, is it because 1/3
is casted to an int so it equals zero?
Yes, that's exactly it.
what does the '.' means in Python in general, could I append a dot to
any number in order to cast it from int to double?
The . is explicitly making the number a float as 1.0 would be opposed to just 1.
You experience integer division in python 2.
in python 2:
>>> 2/3
0
In python 3:
>>> 2/3
0.6666666
If you want the python3 behaviour in python2 you can do
from __future__ import division
as your first import.
For the integer division, use
>>> 2 // 3
0
Or you can use 2.0 / 3.0 to use floats.
In python 2.x, dividing integers defaults to floor division, so any non-integer quotient automatically rounds down to the nearest integer for example
>>> 1/3
0
>>> 5/2
2
So when you try to calculate 27 ** (1/3) you are just calculating 27 ** 0
There are numerous workarounds to the problem, the simplest way would be to just use floating points in the exponent - (1.0/3.0), or even just (1/3.0). However, if you were to be doing a lot of these calculations it might become annoying to constantly type out all the numbers in floating point form. In this case, you could use the future module to utilize Python 3.x division behavior, which always results in a floating point value:
>>> from __future__ import division
>>> 1/3
0.3333333333333333
This way the calculation will never default to floor division. And if at some point you want floor division in the same program, you can just use the // operator to get behavior similar to python 2.x integer division, like so:
>>> 1//3
0

Reasoning for math bug fix in Python [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 4 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

Dividing double values and int values in one array in Python? [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 4 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

Python 2.0 gives -9/4 as -3? shouldnt it be -2?

I am using Python 2.0. I tried doing -9/4 and was expecting the answer to be -2. However, it returns -3. Now -9/4 is -2.25 and I thought int type would round it up to -2 instead of -3. When I do int(-2.25), it returns -2. Can anyone please explain why int(-9/4) returns -3 but int(-2.25) returns -2?
The two operations simply have different rounding modes. From the int() documentation, (reference)
If x is floating point, the conversion truncates towards zero.
Whereas division rounds down, (reference)
Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.

Why does the division get rounded to an integer? [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 5 months ago.
I was trying to normalize a set of numbers from -100 to 0 to a range of 10-100 and was having problems only to notice that even with no variables at all, this does not evaluate the way I would expect it to:
>>> (20-10) / (100-10)
0
Float division doesn't work either:
>>> float((20-10) / (100-10))
0.0
If either side of the division is cast to a float it will work:
>>> (20-10) / float((100-10))
0.1111111111111111
Each side in the first example is evaluating as an int which means the final answer will be cast to an int. Since 0.111 is less than .5, it rounds to 0. It is not transparent in my opinion, but I guess that's the way it is.
What is the explanation?
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
You're putting Integers in so Python is giving you an integer back:
>>> 10 / 90
0
If if you cast this to a float afterwards the rounding will have already been done, in other words, 0 integer will always become 0 float.
If you use floats on either side of the division then Python will give you the answer you expect.
>>> 10 / 90.0
0.1111111111111111
So in your case:
>>> float(20-10) / (100-10)
0.1111111111111111
>>> (20-10) / float(100-10)
0.1111111111111111
In Python 2.7, the / operator is an integer division if inputs are integers:
>>>20/15
1
>>>20.0/15.0
1.33333333333
>>>20.0/15
1.33333333333
In Python 3.3, the / operator is a float division even if the inputs are integer.
>>> 20/15
1.33333333333
>>>20.0/15
1.33333333333
For integer division in Python 3, we will use the // operator.
The // operator is an integer division operator in both Python 2.7 and Python 3.3.
In Python 2.7 and Python 3.3:
>>>20//15
1
Now, see the comparison
>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b
For the above program, the output will be False in Python 2.7 and True in Python 3.3.
In Python 2.7 a = 1.75 and b = 1.
In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.
You need to change it to a float BEFORE you do the division. That is:
float(20 - 10) / (100 - 10)
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
Make at least one of them float, then it will be float division, not integer:
>>> (20.0-10) / (100-10)
0.1111111111111111
Casting the result to float is too late.
In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.
Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.
Try casting one of the operands of "/" to be a float:
float(20-10) / (100-10)
You're casting to float after the division has already happened in your second example. Try this:
float(20-10) / float(100-10)
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't ints, but Sage Integer class elements. Still, worth mentioning as a part of the Python ecosystem.
Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.
In Python 3, the “//” operator works as a floor division for integer and float arguments. However, the operator / returns a float value if one of the arguments is a float (this is similar to C++)
eg:
# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)
Output:
2
-3
# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)
Output:
2.5
-2.5
ref: https://www.geeksforgeeks.org/division-operator-in-python/

Categories

Resources