Newbie: strange int() behaviour
Steve Holden
sholden at holdenweb.com
Tue Dec 3 21:44:55 EST 2002
-----------------------------------------------------------------------
"Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message
news:h03H9.10939$361.7980 at nwrddc04.gnilink.net...
> > My very first python script calculates a value for a given number,
prints
> > out a number of line conisting of stars (half the number) and the value
> > itself.
> >
> > Out of some strange reason it looks like 100 / 2 is in one case 49. Why?
> >
> > The main loop:
> > for i in range (80,100,1):
> > val = fuz.process("temp",i,"speed")
>
> Add this line:
> print val # Will reveal that fuz.process returns
> # slightly less than 100.0000 for i=87
>
> > half = val /2
>
> Here is the problem.
> Val is a floating point number slightly less than 100.0
> and the / 2 gives floor division, truncating to 49.
> Try this line instead:
>
> half = round(val / 2.0, 3)
>
> > length = int(half)
> > stars= length * "*"
> > print "%s %s (%f) stars: %s" % (i,stars,val,length)
>
There's enough confusion about integer division, so I felt it necessary to
pick a nit here. The division is NOT an integer division of any kind.
Currently, division gives a float result if either or both operands is a
float. So what's actually happening is that (just less than 100.0) / 2 is
giving (just less than 50.0) and the int() function is removing the
fractional part to give 49.
Fortunately your proposed solution is correct, I am just ensuring that the
division operator doesn't get misunderstood worse than it already is :-)
regards
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
Previous .sig file retired to www.homeforoldsigs.com
More information about the Python-list
mailing list