hypot, hypotf, hypotl

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       hypotf( float x, float y );
(1) (C99 起)
double      hypot( double x, double y );
(2) (C99 起)
long double hypotl( long double x, long double y );
(3) (C99 起)
在标头 <tgmath.h> 定义
#define hypot( x, y )
(4) (C99 起)
1-3) 计算 xy 平方和的平方根,而不会在计算的中间阶段有过度的上溢或下溢。
4) 泛型宏:若任何实参拥有 long double 类型,则调用函数的 long double 版本。否则,若任何实参拥有整数类型或 double 类型,则调用函数的 double 版本。否则,调用函数的 float 版本。

此函数计算的值是直角边长度为 xy 的直角三角形的斜边长,或点 (x, y) 距原点 (0, 0) 的距离,或复数 x+iy 的绝对值。

参数

x - 浮点值
y - 浮点值

返回值

若不出现错误,则返回直角三角形的斜边,x2
+y2

若出现上溢所致的值域错误,则返回 +HUGE_VAL+HUGE_VALF+HUGE_VALL

若出现下溢所致的值域错误,则返回(舍入后的)正确结果。

错误处理

报告 math_errhandling 中指定的错误。

若实现支持 IEEE 浮点算术(IEC 60559),则

  • hypot(x, y)hypot(y, x)hypot(x, -y) 等价
  • 若实参之一为 ±0,则 hypot 等价于以非零实参调用 fabs
  • 若实参之一为 ±∞,则 hypot 返回 +∞,即使另一参数为 NaN
  • 否则,若任何实参为 NaN,则返回 NaN

注解

实现通常保证小于 1 ulp(最后位置单位)的精度:GNUBSD

hypot(x, y) 等价于 cabs(x + I*y)

POSIX 指定仅若两个实参均为非正规且正确结果亦为非正规才可以出现下溢(这禁止朴素实现)。

hypot(INFINITY, NAN) 返回 +∞,但 sqrt(INFINITY * INFINITY + NAN * NAN) 返回 NaN。

示例

#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    // 典型用法
    printf("笛卡尔坐标 (1,1) 是极坐标 (%f,%f)\n", hypot(1,1), atan2(1, 1));
    // 特殊值
    printf("hypot(NAN,INFINITY) = %f\n", hypot(NAN, INFINITY));
 
    // 错误处理
    errno = 0;
    feclearexcept(FE_ALL_EXCEPT);
    printf("hypot(DBL_MAX,DBL_MAX) = %f\n", hypot(DBL_MAX, DBL_MAX));
    if (errno == ERANGE)
        perror("    errno == ERANGE");
    if (fetestexcept(FE_OVERFLOW))
        puts("    FE_OVERFLOW raised");
}

可能的输出:

笛卡尔坐标 (1,1) 是极坐标 (1.414214,0.785398)
hypot(NAN,INFINITY) = inf
hypot(DBL_MAX,DBL_MAX) = inf
    errno == ERANGE: Numerical result out of range
    FE_OVERFLOW raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.7.3 The hypot functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.4.3 The hypot functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.7.3 The hypot functions (第 181 页)
  • 7.25 Type-generic math <tgmath.h> (第 272-273 页)
  • F.10.4.3 The hypot functions (第 382 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.7.3 The hypot functions (第 248 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.4.3 The hypot functions (第 524 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.7.3 The hypot functions (第 229 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.4.3 The hypot functions (第 461 页)

参阅

(C99)(C99)
计算一个数的给定次幂(xy
(函数)
(C99)(C99)
计算平方根(x
(函数)
(C99)(C99)(C99)
计算立方根(3x
(函数)
(C99)(C99)(C99)
计算复数的模(绝对值)
(函数)