why does python round down? eg -12/10 = -2 - python

I saw a twitter post pointing out that -12/10 = -2 in Python. What causes this? I thought the answer should (mathematically) be one. Why does python "literally" round down like this?
>>> -12/10
-2
>>> 12/10
1
>>> -1*12/10
-2
>>> 12/10 * -1
-1

This is due to int rounding down divisions. (aka Floor division)
>>> -12/10
-2
>>> -12.0/10
-1.2
>>> 12/10
1
>>> 12.0/10
1.2

This is known as floor division (aka int division). In Python 2, this is the default behavior for -12/10. In Python 3, the default behavior is to use floating point division. To enable this behavior in Python 2, use the following import statement:
from __future__ import division
To use floor division in Python 3 or Python 2 with this module imported, use //.
More information can be found in the Python documentation, "PEP 238: Changing the Division Operato".

Related

Python:why 10 / -7 is -2 in python? [duplicate]

Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:
>>> 6/3
2
>>> 6//3
2
In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.
You can find a detailed description at PEP 238: Changing the Division Operator.
Python 2.x Clarification:
To clarify for the Python 2.x line, / is neither floor division nor true division.
/ is floor division when both args are int, but is true division when either of the args are float.
// implements "floor division", regardless of your type. So
1.0/2.0 will give 0.5, but both 1/2, 1//2 and 1.0//2.0 will give 0.
See PEP 238: Changing the Division Operator for details.
/ → Floating point division
// → Floor division
Let’s see some examples in both Python 2.7 and in Python 3.5.
Python 2.7.10 vs. Python 3.5
print (2/3) ----> 0 Python 2.7
print (2/3) ----> 0.6666666666666666 Python 3.5
Python 2.7.10 vs. Python 3.5
print (4/2) ----> 2 Python 2.7
print (4/2) ----> 2.0 Python 3.5
Now if you want to have (in Python 2.7) the same output as in Python 3.5, you can do the following:
Python 2.7.10
from __future__ import division
print (2/3) ----> 0.6666666666666666 # Python 2.7
print (4/2) ----> 2.0 # Python 2.7
Whereas there isn't any difference between floor division in both Python 2.7 and in Python 3.5.
138.93//3 ---> 46.0 # Python 2.7
138.93//3 ---> 46.0 # Python 3.5
4//3 ---> 1 # Python 2.7
4//3 ---> 1 # Python 3.5
As everyone has already answered, // is floor division.
Why this is important is that // is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions.
The behavior of / can change depending on:
Active __future__ import or not (module-local)
Python command line option, either -Q old or -Q new
>>> print 5.0 / 2
2.5
>>> print 5.0 // 2
2.0
Python 2.7 and other upcoming versions of Python:
Division (/)
Divides left hand operand by right hand operand
Example: 4 / 2 = 2
Floor division (//)
The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):
Examples: 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
Both / division and // floor division operator are operating in similar fashion.
The double slash, //, is floor division:
>>> 7//3
2
// is floor division. It will always give you the integer floor of the result. The other is 'regular' division.
The previous answers are good. I want to add another point. Up to some values both of them result in the same quotient. After that floor division operator (//) works fine but not division (/) operator:
>>> int(755349677599789174 / 2) # Wrong answer
377674838799894592
>>> 755349677599789174 // 2 # Correct answer
377674838799894587
The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point.
>>>print 5//2
2
>>> print 5.0//2
2.0
>>>print 5//2.0
2.0
>>>print 5.0//2.0
2.0
Python 3.x Clarification
Just to complement some previous answers.
It is important to remark that:
a // b
Is floor division. As in:
math.floor(a/b)
Is not int division. As in:
int(a/b)
Is not round to 0 float division. As in:
round(a/b,0)
As a consequence, the way of behaving is different when it comes to positives an negatives numbers as in the following example:
1 // 2 is 0, as in:
math.floor(1/2)
-1 // 2 is -1, as in:
math.floor(-1/2)
Python 3
Operation
Result
Notes
x / y
quotient of x and y
x // y
floored quotient of x and y
(1)
Notes:
Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.
Python 2
Operation
Result
Notes
x / y
quotient of x and y
(1)
x // y
(floored) quotient of x and y
(4)(5)
Notes:
1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.
4. Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate.
5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
Summary
x//y : EXACT integer division
int(x/y) OR math.floor(x/y): INEXACT integer division (but almost correct)
x/y: floating point division (that has the loss of significance)
Remarkable Calculation Result
import math
N = 1004291331219602346 # huge number
print(N//100) #=> 10042913312196023 is correct answer
print(math.floor(N/100)) #=> 10042913312196024 is wrong answer
print(math.ceil(N/100)) #=> 10042913312196024 is wrong answer
print(int(N/100)) #=> 10042913312196024 is wrong answer
Consideration
I think about the evaluation of int(x/y).
At first, Python evaluate the expression x/y and get INEXACT floating number z.
Second, Python evaluate the expression int(z).
We get a wrong result when the loss of significance cannot be ignored.
// is floor division. It will always give you the floor value of the result.
And the other one, /, is the floating-point division.
In the following is the difference between / and //;
I have run these arithmetic operations in Python 3.7.2.
>>> print (11 / 3)
3.6666666666666665
>>> print (11 // 3)
3
>>> print (11.3 / 3)
3.7666666666666667
>>> print (11.3 // 3)
3.0
5.0//2 results in 2.0, and not 2, because the return type of the return value from // operator follows Python coercion (type casting) rules.
Python promotes conversion of lower data type (integer) to higher data type (float) to avoid data loss.

Python division operator gives different results

In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.
Example:
5/2 gives 2
and
-5/2 gives -3
How to get -2 when I divide -5/2 ?
As of this accepted answer:
> int(float(-5)/2)
-2
> int(float(5)/2)
2
You should enclose division in expression like below
print -(5/2)
This happens due to python rounding integer division. Below are a few examples. In python, the float type is the stronger type and expressions involving float and int evaluate to float.
>>> 5/2
2
>>> -5/2
-3
>>> -5.0/2
-2.5
>>> 5.0/2
2.5
>>> -5//2
-3
To circumvent the rounding, you could leverage this property; and instead perform a calculation with float as to not lose precision. Then use math module to return the ceiling of that number (then convert to -> int again):
>>> import math
>>> int(math.ceil(-5/float(2)))
-2
You need to use float division and then use int to truncate the decimal
>>> from __future__ import division
>>> -5 / 2
-2.5
>>> int(-5 / 2)
-2
In Python 3, float division is the default, and you don't need to include the from __future__ import division. Alternatively, you could manually make one of the values a float to force float division
>>> -5 / 2.0
-2.5
>>> import math
>>> math.ceil(float(-5)/2)
-2.0

Python float formatting conundrum [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

Weird behaviour in python vs. R in calculating logarithm [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

Converting to float without truncation [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

Categories