Integer multiplication overflow.

Tim Peters tim_one at email.msn.com
Sun Oct 8 14:47:11 EDT 2000


[/F]
> there's an implementation in the standard distribution:
>
>     Demo/classes/Rat.py

[Alex Martelli]
> There does not seem to be such a file (nor, indeed, any Demo
> directory) in the 2.0b2 distribution (Windows version).

Right, the Demo directory is only in the source distribution.  The Windows
distribution is designed more to minimize confusion for newbies <ahem -- but
the Demo directory does have a lot of, umm, ancient crap, in it, and Guido
doesn't want to include it in the Windows distro before it gets pruned and
updated>.

Anyway, the Rat.py therein is indeed more of a demo than a seriously usable
rational class.  For example,

	def __add__(a, b):
		try:
			return rat(a.__num * b.__den + b.__num * a.__den,
				   a.__den * b.__den)
		except OverflowError:
			return rat(long(a.__num) * long(b.__den) +
				   long(b.__num) * long(a.__den),
				   long(a.__den) * long(b.__den))

That's fine so far as it goes, but if that's "good enough" you can whip up a
workalike yourself in less time than it takes to get and unpack the source
distribution <wink>.  The difficulty here is that the algorithm is naive,
often creating much larger ints than are necessary, and leaving it to rat()
to discover and divide out large common factors after the fact;
"sophisticated" algorithms compute results in lowest terms directly; since
multiplication and division of longs in Python take time quadratic in the
number of bits, this can make a huge difference in runtime.

I've got a suitably convoluted Rational package under development, including
a huge number of options for exact and rounded I/O (also necessary for
serious work), but haven't had time to even look at it since April.

spent-a-lot-more-time-writing-python-before-i-was-paid-to<wink>-ly y'rs
    - tim






More information about the Python-list mailing list