Python float formatting conundrum [duplicate] - 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 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.

Related

i am trying to make a function that returns price excluding vat [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/

Gamma function in python doesn't plot what I expected [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.

Python: Temperature converter only works f to c, not other way around? [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