开发者

Why doesn't this division work in Python? [duplicate]

This question already has answers here: Why does the division get rounded to an integer? [duplicate] (13 answers) Closed 7 years ago.

Consider:

>>> numerator = 29
>>> denom = 1009
>>> print str(flo开发者_如何转开发at(numerator/denom))
0.0

How do I make it return a decimal?


Until version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. See: PEP 238

>>> n = 29
>>> d = 1009
>>> print str(float(n)/d)
0.0287413280476

In Python 2 (and maybe earlier) you could use:

>>> from __future__ import division
>>> n/d
0.028741328047571853


In Python 2.x, division works like it does in C-like languages: if both arguments are integers, the result is truncated to an integer, so 29/1009 is 0. 0 as a float is 0.0. To fix it, cast to a float before dividing:

print str(float(numerator)/denominator)

In Python 3.x, the division acts more naturally, so you'll get the correct mathematical result (within floating-point error).


In your evaluation you are casting the result, you need to instead cast the operands.


print str(float(numerator)/float(denom))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜