Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Companion to hypot()

The hypot function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as

double hypot(double a, double b)
{
  return sqrt(a*a + b*b);
}

I find myself with the need for companion functionality: given a side and the hypotenuse of a triangle, find the third side (avoiding under/overflow). I can think of a few ways to do this, but wondered if there was an existing "best practice"?

My target is Python, but really I'm looking for algorithm pointers.


Thanks for the replies. In case anyone is interested in the result, my C99 implementation can be found here and a Python version here, part of the Hypothesis project.

like image 800
jjg Avatar asked Mar 09 '18 10:03

jjg


People also ask

What is hypot in c++?

The hypot() function in C++ returns the square root of sum of square of arguments passed.

How do you use hypot in Python?

Python hypot() is an inbuilt function that calculates the hypotenuse of a right triangle. It's a method of math module. hypot(x,y): x,y are the two sides of the right triangle, hypotenuse = √x * x + y * y.

What is JavaScript hypot?

hypot() function in JavaScript is used to calculate the square root of the sum of squares of numbers passed to it as arguments. It is basically used to find the hypotenuse of a right-angled triangle or the magnitude of a complex number. Math.

What is Matlab hypot?

Square root of sum of squares (hypotenuse) - MATLAB hypot.


1 Answers

The first thing to do is factorize:

b = sqrt(h*h - a*a) = sqrt((h-a)*(h+a))

We have not only avoided some overflow, but also gained accuracy.

If any factor is close to 1E+154 = sqrt(1E+308) (max with IEEE 754 64 bits float) then we must also avoid overflow:

sqrt((h-a)*(h+a)) = sqrt(h-a) * sqrt(h+a)

This case is very unlikely, so the two sqrt's are justified, even if its slower than just a sqrt.

Notice that if h ~ 5E+7 * a then h ~ b which means that there are not enough digits to represent b as different from h.

like image 87
Ripi2 Avatar answered Oct 03 '22 03:10

Ripi2