a more precise distance algorithm

Christian Gollwitzer auriocus at gmx.de
Mon May 25 16:27:14 EDT 2015


Am 25.05.15 um 21:21 schrieb ravas:
> 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?

Yes. Valid for floating point math, which can overflow and lose precision.

> Does it apply to python?

Yes. Python uses floating point math by default

> Any other thoughts? :D
>
> My imagining:
>
> def distance(A, B):

Wrong. Just use the built-in function Math.hypot() - it should handle 
these cases and also overflow, infinity etc. in the best possible way.

Apfelkiste:~ chris$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> import math
 >>> math.hypot(3,4)
5.0

	Christian



More information about the Python-list mailing list