It is clearly possible to compute sqrt(x*x + y*y)
without using the hypot(x,y)
function. Why is this function part of the standard?
Is this related to some internal (hardware based) optimizations?
It is clearly possible to compute sqrt(x*x + y*y)
without using the hypot(x,y)
function. Why is this function part of the standard?
Is this related to some internal (hardware based) optimizations?
The hypot
function performs this calculation while avoiding overflows.
Section 7.12.7.3p2 of the C standard regarding the hypot
function states:
The
hypot
functions compute the square root of the sum of the squares ofx
andy
, without undue overflow or underflow. A range error may occur.
In addition to hypot(x,y)
avoiding undo overflow (@bush) and potentially providing a more accurate answer (@Ian Abbot) than sqrt(x*x + y*y)
, a subtle corner case is defined.
If std library adheres to ANSI/IEEE 754, __STDC_IEC_559__
defined, then
hypot(±∞; y) returns +∞, even if y is a NaN. C17dr § F.10.4.3
sqrt(x*x + y*y)
would not.
There might be a cost: Why hypot() function is so slow?. It is a quality of implementation concern.
Is this related to some internal (hardware based) optimizations?
@njuffa discusses this.
The value of the sqrt(x*x + y*y)
doesn't have to be equal to the value of the hypot(x, y)
. Example for demonstration:
#include <stdio.h>
#include <math.h>
#include <float.h>
int main (void)
{
double x = DBL_MAX/2, y = x;
printf("x = %g, y = %g\n", x, y);
printf("sqrt(x*x + y*y) = %g\n", sqrt(x * x + y * y));
printf("hypot(x*x + y*y) = %g\n", hypot(x, y));
}
The hypot(x,y)
gives the (approximately) correct result even if the arithmetical value of x*x + y*y
is greater than DBL_MAX
.