Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to double Python [duplicate]

Tags:

python

I can't seem to find the answer to this on this site, though it seems like it would be common enough. I am trying to output a double for the ratio of number of lines in two files.

#Number of lines in each file
inputLines = sum(1 for line in open(current_file))
outputLines = sum(1 for line in open(output_file))

Then get the ratio:

ratio = inputLines/outputLines

But the ratio always seems to be an int and rounds even if I initialize it like:

ratio = 1.0

Thanks.

like image 578
The Nightman Avatar asked Jul 20 '15 15:07

The Nightman


People also ask

How do you convert int to double in Python?

You need to cast one of the terms to a floating point value. Either explicitly by using float (that is ratio = float(a)/b or ratio=a/float(b) ) or implicitly by adding 0.0 : ratio = (a+0.0)/b . If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.

Can I convert int to double?

We can convert int value to Double object by instantiating Double class or calling Double. valueOf() method.

Can we convert int to float in Python?

To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.


2 Answers

In python 2, the result of a division of two integers is always a integer. To force a float division, you need to use at least one float in the division:

ratio = float(inputLines)/outputLines

Be careful not to do ratio = float(inputLines/outputLines): although that results in a float, it's one obtained after doing the integer division, so the result will be "wrong" (as in "not what you expect")

In python 3, the integer division behavior was changed, and a division of two integers results in a float. You can also use this functionality in python 2.7, by putting from __future__ import division in the begging of your files.


The reason ratio = 1.0 does not work is that types (in python) are a property of values, not variables - in other words, variables don't have types.

a= 1.0 # "a" is a float
a= 1   # "a" is now a integer
like image 167
loopbackbee Avatar answered Oct 02 '22 08:10

loopbackbee


Are you using Python 2.x?

Try using

>>> from __future__ import division
>>> ratio = 2/5
0.4

to get a float from a division.

Initializing with ratio = 1.0 doesn't work because with ratio = inputLines/outputLines you are re-assigning the variable to int, no matter what it was before.

like image 28
adrianus Avatar answered Oct 02 '22 09:10

adrianus