a more precise distance algorithm

felix felix at epepm.cupet.cu
Mon May 25 16:06:06 EDT 2015


El 25/05/15 15:21, ravas escribió:
> 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)
I don't know if precision lose fits here but the second way you gave to 
calculate c is just Math. Nothing extraordinary here.

c = a * sqrt(1 + b^2 / a^2)
c = sqrt(a^2(1 + b^2 / a^2)) applying the inverse function to introduce 
a inside the square root
c = sqrt(a^2 + a^2*b^2/a^2) then just simplify
c = sqrt(a^2 + b^2)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150525/b7c91065/attachment-0001.html>


More information about the Python-list mailing list