On Mon, May 25, 2015 at 1:21 PM, ravas <ra...@outlook.com> wrote:
> 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

This branch is incorrect because a could be negative.

You don't need this anyway; the a == 0 branch is only there because of
the division by a in the else branch.

>     else:
>         return a * sqrt(1 + (b / a)**2)

Same issue; if a is negative then the result will have the wrong sign.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to