Convert int to float

Bryan Olson fakeaddress at nowhere.org
Sun Mar 16 21:29:30 EDT 2008


sturlamolden wrote:
> Guido van Brakel wrote:
> 
>>> def gem(a):
>>>     g = sum(a) / len(a)
>>>     return g
> 
>> It now gives a int, but i would like to see floats. How can integrate
>> that into the function?
> 
> You get an int because you are doing integer division. Cast one int to
> float.
> 
> def gem(a):
>    g = sum(a) / float(len(a))
>    return g

An alternative is to multiply by 1.0.

     def gem(a):
         g = 1.0 * sum(a) / len(a)
         return g

The gem function is well-defined on sequences of complex numbers,
in which case the float() method will raise a TypeError, while
the 1.0* method will return the complex result. It may not be
what van Brakel wants here, but it's an alternative to keep in mind.

And I find it easier to type.

-- 
--Bryan



More information about the Python-list mailing list