Hypot
06.15
Diposting oleh Melany Christy
Motivation and usage
Calculation of the length of the hypotenuse of a triangle is possible to do using the square root function but hypot(x, y) avoids possible problems with very large or very small numbers.
The magnitude of the hypotenuse from (0, 0) to (x, y) can be calculated using:
However the squares of very large or small values of x and y may exceed the range of machine precision when calculated on a computer, leading to an inaccurate result (see underflow, overflow). The hypot function was designed to calculate the result without causing this problem.
The hypot function may typically be used together with the atan2 function to convert from Cartesian to polar coordinates:
- r = hypot(x, y) θ = atan2(y, x)
Implementation
The difficulty with the naive implementation is that x² or y² may over- or underflow, unless the intermediate result is computed with extended precision. A common implementation technique is to exchange the values, if necessary, so that |x|>|y|, and then use the equivalent form:
The computation of y/x cannot overflow, and underflows compute the correct result. The square root is computed over a value between 1 and 2. Finally, the multiplication by |x| cannot underflow, and overflows only when the result is too large to represent.
Programming language support
The function is present in several programming languages:
- C99
- Apple's PowerPC Numerics [1]
- Matlab[2]
- Pascal [3]
- PHP[4]
- Java (since version 1.5)[5]
Some C90 and C++ libraries have provided a hypot function.
Posting Komentar