Posts Tagged ‘python code’

A sort of request…

February 16, 2008

Every so often (well, ok, daily) I check my wordpress stats to see how many people have found a link pointing at my ramblings, or have unwittingly found it using a search engine. Indeed, much of the entertainment I get out of this site derives from the search terms used.

One used yesterday was “program to see if a triangle is equilateral”. Obviously I’ve never answered that question here, an omission I should put right immediately.

There are several ways to tell if a triangle is equilateral: the two most obvious ones are to check that all of the sides have the same length, or to check that all of the angles are 60º; you can also check that two sides are the same length and that the angle between them is 60º.

The easiest one to implement is the same-length check. Let’s say you have three points – we need to see if the distance between each pair of points is the same. That distance is sqrt(x^2 + y^2 + z^2). Because we’re only checking for equality, we don’t even need to take the square root. Our python code is something like:

class Point:
# Class to keep the points tidy
def __init__(self, x,y,z):
  self.x = x
  self.y = y
  self.z = z

def distanceSquared(P, Q):
  dx2 = (P.x - Q.x) ** 2
  dy2 = (P.y - Q.y) ** 2
  dz2 = (P.z - Q.z) ** 2
  return dx2 + dy2 + dz2

def isEquilateral(A, B, C):
  ab2 = distanceSquared(A, B)
  ac2 = distanceSquared(B, C)
  bc2 = distanceSquared(A, C)
  if ab2 != ac2 or ab2 != bc2:
    return 0
    return 1

A = Point(0.,0.,0.)
B = Point(1.,1.,0.)
C = Point(0.,1.,1.)
D = Point(1.,0.,0.)
print isEqulilateral( A, B, C)
# should return 1
print isEquilateral ( A, B, D)
# should return 0