Fun with numbers - dammit, but I want a cast!

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Aug 11 08:56:44 EDT 2003


Graham Nicholls <graham at rockcons.co.uk> wrote in
news:3f378fac$0$10778$afc38c87 at auth.uk.news.easynet.net: 

> eg      
>         xscale=xframe/img_x
> 
> where xframe will be say 300, and img_x will be 1800
> xscale has the value 0.
> 
> I've tried doing img_x=1.0 to force it to be a float, but I'm getting
> a bit frustrated as it seems to make no difference - once
> image.getsize returns the (integer) value of the x size, it simply
> converts back to an int. 

Variables don't have types in Python, objects have types. Assigning a float 
object to a variable doesn't have any effect on the type of the next 
object assigned to the same variable.

To get the behaviour you want either convert at least one of your values to 
a float:

     xscale = float(xframe)/img_x

or add the following 'magic' line to the top of your sourcefile:

    from __future__ import division

If your file has that line at the top, division will behave more the way 
you expect: casting to float automatically whenever you divide integers.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list