This is because python integer is meant to truncate down to the lowest value. You have a bunch of options to get around this:
>>> 5 / 2
2
Option 1
Cast one of your values as float and python will automatically up-cast all other int types
>>> 5 / 2
2
>>> float(5) / 2
2.5
Correction to your code:
def average_fitness(haploid_list):
return float(sum(haploid_list[0])) / len(haploid_list)
Option 2
Add this to the top of your script
from __future__ import division
Now, 5 / 2
will yield 2.5
and you don't need to change your average_fitness
method as shown in option 1. The __future__
refers to python3 in which the /
operator by default performs float divisions. By import that feature, you will now use the float
division operator /
everywhere in your code instead of python2's int
division operator
Option 3
You can replace the /
with the //
operator
>>> 5 / 2
2
>>> 5 // 2
2.5
Correction to your code:
def average_fitness(haploid_list):
return float(sum(haploid_list[0])) // len(haploid_list)