What can be difficult in calculating the hypotenuse?

Original author: John D. Cook
  • Transfer
  • Tutorial
In libraries of various programming languages, a function can often be turned on to calculate the hypotenuse of a right triangle (or you yourself can write such a function to solve a particular problem).

At first glance, this may seem like a trivial task, right? If the sides of the triangle are x and y , then, formally, the formula for calculating the hypotenuse will be:

sqrt(x*x + y*y)

This works theoretically, but in practice this approach can lead to an error. If the value of x is large enough, then the calculation of x * x can lead to an overflow of the data type (no data type is safe from this unless long arithmetic is considered), and the result of the calculations will be infinity.

One way to avoid the possibility of overflow is the following sequence of actions:

max = maximum(|x|, |y|);
min = minimum(|x|, |y|);
r = min / max;
return max*sqrt(1 + r*r);

Note that the value of the radical expression lies in the range from 1 to 2, which in no way can lead to overflow when calculating the square root. The only place where overflow can happen is the final multiplication. But, if the overflow happened, it only means that the result is so large that it can not be accommodated in the data type used, and this is not the problem of choosing an algorithm, but the problem of choosing a data type.

In order to see how the above algorithm can succeed while the decision to fall head on, we give a small example. Let M be the largest number that can be represented by the selected data type. For the data type double, M will be of the order of 10 308 . Let x andy equivalent value of 0.5 M . The algorithm should return a value approximately equal to 0.707 M , which should not overflow the selected data type. But a head-on solution will not give the right answer, while the proposed algorithm will succeed.

For the sake of interest, I checked the standard function (hypot or _hypot) included in math.h, and the result was pleased.

The conclusion I made for myself: if some function is included in the library that at first glance seems elementary and is written in two lines, then there is a high probability that this is done for a reason and there are some deep reasons for such a decision .

Using the link to the original material, comments can be found on the question of whether accuracy will not be lost with this method of finding the hypotenuse.

Also popular now: