Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numbers

Consider:

>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0

How do I make it return a decimal?

like image 262
TIMEX Avatar asked Nov 24 '09 01:11

TIMEX


People also ask

How do you do double division in Python?

The division result of two numbers can be an integer or a floating-point number. In python version 3+, both the single slash (/) operator and the double slash (//) operator are used to get the division result containing the floating-point value.

Does a division in Python always result in float?

// int DivisionThe / operator always produce a float. However many algorithms make the most sense if all of the values are kept as ints, so we need a different sort of division operator that produces ints. In Python the int-division operator // rounds down any fraction, always yielding an int result.

How does division work in Python?

In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

Why does division in Python return a float?

Behavior of the division operator in Python 2.7 and Python 3 // is not "used for integer output". // is the result of the floor() function to the result of the division, which in turns yields an integer if the two operands are integers and a float if at least one of them is a float, for types coherence.


1 Answers

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
like image 171
miku Avatar answered Nov 11 '22 07:11

miku