📜 ⬆️ ⬇️

What can be difficult in calculating the hypotenuse?

In libraries of various programming languages, a function can often be included 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, isn't it? 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 immune from this, if you do not consider long arithmetic), and the result of the calculations will be infinity.

One option 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 radicand expression lies in the interval from 1 to 2, which in no way can lead to overflow in calculating the square root. The only place in which overflow can occur is the final multiplication. But, if overflow has occurred, it only means that the result is so great that it cannot be contained in the data type used, and this is no longer a problem of choosing an algorithm, but a problem of choosing a data type.

In order to see how the above algorithm can succeed while the solution in the forehead falls, we give a small example. Let M be the largest number that can be represented by the selected data type. For double data type, M will be about 10 308 . Let x and y be equivalent to 0.5 M. The algorithm should return a value of approximately 0.707 M , which should not overwhelm the selected data type. But a solution to the forehead will not give the correct 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 I was pleased with the result.

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

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

Source: https://habr.com/ru/post/165061/


All Articles