sqrt, sqrtf, sqrtl

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       sqrtf( float arg );
(1) (C99 起)
double      sqrt( double arg );
(2)
long double sqrtl( long double arg );
(3) (C99 起)
在标头 <tgmath.h> 定义
#define sqrt( arg )
(4) (C99 起)
1-3) 计算 arg 的平方根。
4) 泛型宏:若 arg 拥有 long double 类型,则调用 sqrtl。否则,若 arg 拥有整数类型或 double 类型,则调用 sqrt。否则调用 sqrtf。若 arg 为复数或虚数,则宏调用对应复数函数(csqrtfcsqrtcsqrtl)。

参数

arg - 浮点值

返回值

若不出现错误,则返回 arg 的平方根(arg)。

若出现定义域错误,则返回实现定义值(支持的平台上为 NaN)。

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

错误处理

报告 math_errhandling 中指定的错误。

arg 小于零则出现定义域错误。

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

  • 若实参小于 -0,则引发 FE_INVALID 并返回 NaN。
  • 若实参为 +∞ 或 ±0,则返回不修改的参数。
  • 若实参为 NaN,则返回 NaN。

注解

IEEE 标准要求 sqrt 为准确。其他要求为准确的运算只有算术运算符和函数 fma。舍入到返回类型后(用默认舍入模式),sqrt 的结果与无限精度结果不可辨别。换言之,误差小于 0.5 ulp。其他函数,含 pow,不受这种制约。

示例

#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    // 正常使用
    printf("sqrt(100) = %f\n", sqrt(100));
    printf("sqrt(2) = %f\n", sqrt(2));
    printf("黄金比 = %f\n", (1 + sqrt(5)) / 2);
 
    // 特殊值
    printf("sqrt(-0) = %f\n", sqrt(-0.0));
 
    // 错误处理
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("sqrt(-1.0) = %f\n", sqrt(-1));
    if (errno == EDOM)
        perror("    errno == EDOM");
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID was raised");
}

可能的输出:

sqrt(100) = 10.000000
sqrt(2) = 1.414214
黄金比 = 1.618034
sqrt(-0) = -0.000000
sqrt(-1.0) = -nan
    errno = EDOM: Numerical argument out of domain
    FE_INVALID was raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.7.5 The sqrt functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.4.5 The sqrt functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.7.5 The sqrt functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.4.5 The sqrt functions (第 TBD 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.7.5 The sqrt functions (第 249 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.4.5 The sqrt functions (第 525 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.7.5 The sqrt functions (第 229-230 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.4.5 The sqrt functions (第 462 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.5.5.2 The sqrt function

参阅

(C99)(C99)
计算一个数的给定次幂(xy
(函数)
(C99)(C99)(C99)
计算立方根(3x
(函数)
(C99)(C99)(C99)
计算两个给定数平方和的平方根(x2
+y2

(函数)
(C99)(C99)(C99)
计算复数平方根
(函数)