Integers and Floats

skaller skaller at maxtal.com.au
Sun Oct 17 10:01:50 EDT 1999


Gerrit Holl wrote:
> >>> 131 / 4 * 4
> 128
> 
> I think the ouput of the first two statement is ok, but why can't python store
> an integer and a float as the same thing? And is the conversion between an
> integer and a float so big? Or are floats just slower? Do I have to do the
> following:
> 
> >>> int(float(131) / 4 * 4)
> 131


Yes. float/float and int/int are two distinct operations, you have
to cast at least one of a pair of integers, to force the
floating operation.

Note that while this is also true in my python implementation Viper,
there is another technique:

	x = rational(131)
	print x / 4 * 4

131

because Viper also supports arbitrary precision
rational arithmetic :-)

Note your formula is suspect: use

	int (float(131) / 4 * 4 + 0.5)

instead. The reason is that rounding errors
may result in the floating answer being

	130.99999999

which is  130 truncated, not 131.
-- 
John Skaller, mailto:skaller at maxtal.com.au
1/10 Toxteth Rd Glebe NSW 2037 Australia
homepage: http://www.maxtal.com.au/~skaller
downloads: http://www.triode.net.au/~skaller




More information about the Python-list mailing list