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

Torsten Marek shlomme at gmx.net
Mon Aug 11 09:09:17 EDT 2003


Graham Nicholls schrieb:
> Hi.
> 
> I'm having some fun with numbers.  I've extraced an image sizes from a jpeg
> file
> 
>         img_x,img_y=image.getsize()
> 
> then I'm trying to  use those sizes to scale the image, but because python
> has decided that they are integers, I keep getting division by zero errors
> 
> 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.  I've
> tried this at the command line, and it seems to confirm that behaviour -
> eg:
> graham at rocklap:~/work/hsb/pdflive> python
> Python 2.3b1 (#3, Jun 17 2003, 23:06:11)
> [GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
>>>>x=1.0
>>>>xf=1.0
>>>>scale=1.0
>>>>x=1800
>>>>xf=300
>>>>scale=xf/x
>>>>scale
> 
> 0
> 
> 
> 
> 
> 
> Heres the relevant code in full:
> 
>         img_x=1.0
>         img_y=1.0
>         img_x,img_y=image.getsize()
>         except "Not_JPEG":
>         if warn:
>                 print ("WARNING: Image file %s is not a jpeg file" % fname)
>                 sys.exit(OPEN_ERR)
> # How many pixels per mm do we have
> #       On a4 paper, using pdfrw ? Docs seem to suggest between 60-160 
> #       which seems a lot.
>                                 
>         xscale=1.0
>         yscale=1.0
>         scale=1.0
>         xscale=1/(xframe/img_x)
>         yscale=1/(yframe/img_y)
>         #import pdb
>         #pdb.set_trace()
>         print ("xscale=%f,yscale=%f"  %(xscale,yscale))
>         scale=min(xscale,yscale) * 100
>         print ("xframe=%d,yframe=%d, x=%d,y=%d scale=%f\n" %(xframe,  yframe,
> img_x, img_y, scale))
>                                         
> I'd really appreciate some help, thanks!
> Graham
The type of a variable does not depend on the type it was initialized with.
You could do
t = 1
t = 1.1
t = "1"
t = [1,]
and the type changes each time. There is no concept of "int xscale" what 
you might have in mind.
You just should convert the integer into a float with
xscale=1/(xframe/float(img_x)).


greetings
Torsten





More information about the Python-list mailing list