I don’t think that the caliber of my posts has necessarily been so high that people will be shocked by overt stupidity from me, but I just discovered some in myself, and stupidity is one of the things that is better shared.

One of the things I’ve had to do very often in Project Euler is figure out whether some long number is an integer or not. So I’ve defined the following function, that I’ve used over and over again:

def is_int(f): return int(f) == f

It actually works pretty well in any number of cases, until the floating point number f starts getting big. However, that doesn’t mean it should be used all of the time.

One place where I’ve used this function incorrectly is figuring out whether a square root is integral, for example, in looking for Pythagorean triplets. It’s much better to test whether a**2+b**2 is square, than whether sqrt(a**2+b**2) is integral. However, since for really huge numbers this requires generating a long list of square integers, I don’t feel too stupid about this. (Does anyone know of a clever way to test whether an integer is a square??)

What I do feel stupid about is in checking whether a rational fraction is integral. I caught myself doing this:

is_int(a/float(b))

which is staggeringly stupid. I was flipping through some of the forum solutions to Project Euler, and noticed one of the Pythonistas was using the much more intelligent

a % b == 0

One of those things that seems stunningly obvious once you see it, but, for whatever reason, I didn’t see it. (Hangs head in shame.)

### Like this:

Like Loading...

*Related*

This entry was posted on February 12, 2008 at 12:45 pm and is filed under Programming, Python.

February 13, 2008 at 4:06 pm

[…] Snake Food Pedal vehicle for traversing abandoned monorailwaySteve Martin on being funnyLandmarks: What Makes the Stars Shine?MPAA admits to lying about college downloadingA Cold-Weather Anthem for the Cold-Hearted « D’oh moment from Project Euler […]

March 2, 2010 at 4:48 pm

Hmmm… when I did the pythagorean triplets at PE, I wrote the following function:

and then did:

March 2, 2010 at 4:49 pm

By the way, it cut off the last 3 0’s from the last if statement…