Evaluate expression as float in Python
I want to write a function which inputs two variables a, b and which returns a开发者_StackOverflow中文版/b as a float irrespective of the types of a and b. Right now I'm doing this as:
def f(a, b):
return float(a)/float(b)
Is there a better way to do this?
Assuming you are using Python2, put this at the top of the file
from __future__ import division
now /
will always give a float. Use //
for the old behaviour.
If you are using Python3, then this is already the default behaviour of /
You could simply force the conversion of one of the operands to the float type, for example:
def f(a, b):
return (a*1.0)/b
It depends. ;)
The safest way is to do what you have, which will work for every numeric type that can be converted to a float
. Some numeric types, such as Fraction
in Python 3, will still return a Fraction
even with the new division (which only affects int
s -- other types define /
for themselves) but your code will properly turn Fraction
s into floats
.
精彩评论