a more precise distance algorithm

ravas ravas at outlook.com
Mon May 25 15:21:46 EDT 2015


I read an interesting comment:
"""
The coolest thing I've ever discovered about Pythagorean's Theorem is an alternate way to calculate it. If you write a program that uses the distance form c = sqrt(a^2 + b^2) you will suffer from the lose of half of your available precision because the square root operation is last. A more accurate calculation is c = a * sqrt(1 + b^2 / a^2). If a is less than b, you should swap them and of course handle the special case of a = 0.
"""

Is this valid? Does it apply to python?
Any other thoughts? :D

My imagining:

def distance(A, B):
    """
    A & B are objects with x and y attributes
    :return: the distance between A and B
    """
    dx = B.x - A.x
    dy = B.y - A.y
    a = min(dx, dy)
    b = max(dx, dy)
    if a == 0:
        return b
    elif b == 0:
        return a
    else:
        return a * sqrt(1 + (b / a)**2)



More information about the Python-list mailing list