BlueStarry BlueStarry - 1 year ago 75
Python Question

Python 2 and Python 3 different behavior on floating point?

Hi consider this code below:

lenght_DNA = len(DNA)
print ("lenght:" + str(lenght_DNA))
a_count = DNA.count('A')
print ("A-count:" + str(a_count))
t_count = DNA.count('T')
print ("T-count:" + str(t_count))
AT_content = (a_count + t_count)/(lenght_DNA)
print ("AT_content:" + str(AT_content))

In Python 2 the final print gives 0 in python 3 a correct decimal number like 0.63blabla.
How do i get the same behavior in Python 2?

Answer Source

The division operator in Python 2 on two integer arguments, which your lengths are, will do integer division. In integer division the fractional part is discarded. In Python 3 this was changed to do floating point division.

There are two solutions:

The first is to cast the arguments to a float:

AT_content = float(a_count + t_count)/(lenght_DNA)

the second is to change the division behaviour to the Python 3 behaviour at the top of your script:

from __future__ import division