{ 2008 01 21 }

## gmpy has rationals

I had an almost-working solution to Project Euler Problem 101 which failed due to floating-point roundoff error. So I wrote my own Python Rational class, with lots of overloaded methods like __add__ and __div__ to handle all the infix math operations. This was not fun, and I never quite got my Rational class perfect, just good enough to let me finish the problem.

The next day, I thought of using gmpy for another Project Euler problem, because it has an is_prime function that's fast for big numbers. (It returns 0 for composite, 1 for prime, and 2 for probable prime.) And while I was reading the docs, I found the mpq rational type inside. Which would have saved me an hour of pain.

Anyway, if you're ever doing math problems in Python, read all of the documentation for both gmpy (the Python library) and GMP (the C library it wraps). GMP is billed primarily as a bignum library, which you don't really need in Python since Python comes with infinite-precision longs. But there's a lot more to it than that.

## Post a Comment

You must be logged in to post a comment.