how to convert an integer to a float?

Antoon Pardon apardon at forel.vub.ac.be
Thu Mar 8 07:29:30 EST 2007


On 2007-03-05, Andrew Koenig <ark at acm.org> wrote:
><yinglcs at gmail.com> wrote in message 
> news:1172621139.954362.196170 at k78g2000cwa.googlegroups.com...
>> Hi, I have the following functions,  but ' dx = abs(i2 - i1)/min(i2,
>> i1)' always return 0, can you please tell me how can i convert it from
>> an integer to float?
>
> I don't think that's what you really want to do.
>
> What you really want is for dx to be a float rather than being truncated to 
> an integer.  Division is going to behave that way in the future, so if you 
> want it to behave that way now, you can write
>
>     from __future__ import division
>
> at the beginning of your program.
>
> If for some reason you don't want to rely on using a version of Python that 
> knows about this future behavior, you might consider
>
>     dx = float(abs(i2 - i1))/min(i2, i1)

I prefer to multiply by 1.0 That has the advantage it continues to work
if your numbers happen to be complex.

-- 
Antoon Pardon



More information about the Python-list mailing list