sqrt, sqrtf, sqrtl
来自 cppreference.cn
定义于头文件 <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 是复数或虚数,则该宏调用相应的复数函数(csqrtf、csqrt、csqrtl)。目录 |
[编辑] 参数
arg | - | 浮点值 |
[编辑] 返回值
如果没有发生错误,则返回 arg 的平方根(√arg)。
如果发生域错误,则返回实现定义的值 (支持 NaN 时返回 NaN)。
如果因下溢发生范围错误,则返回正确结果(舍入后)。
[编辑] 错误处理
错误按 math_errhandling
中指定的方式报告。
如果 arg 小于零,则发生域错误。
如果实现支持 IEEE 浮点运算 (IEC 60559),
- 如果参数小于 -0,则引发 FE_INVALID 并返回 NaN。
- 如果参数是 +∞ 或 ±0,则原样返回。
- 如果参数为 NaN,则返回 NaN。
[编辑] 注意
IEEE 标准要求 sqrt
从无限精度的结果进行正确舍入。特别是,如果精确结果可以在浮点类型中表示,则会生成精确结果。唯一需要此操作的其他操作是算术运算符和函数 fma。其他函数,包括 pow,则不受此限制。
[编辑] 示例
运行此代码
#include <errno.h> #include <fenv.h> #include <math.h> #include <stdio.h> // #pragma STDC FENV_ACCESS ON int main(void) { // normal use printf("sqrt(100) = %f\n", sqrt(100)); printf("sqrt(2) = %f\n", sqrt(2)); printf("golden ratio = %f\n", (1 + sqrt(5)) / 2); // special values printf("sqrt(-0) = %f\n", sqrt(-0.0)); // error handling 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 golden ratio = 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 平方根函数 (p: TBD)
- 7.25 类型通用数学 <tgmath.h> (p: TBD)
- F.10.4.5 平方根函数 (p: TBD)
- C17 标准 (ISO/IEC 9899:2018)
- 7.12.7.5 平方根函数 (p: TBD)
- 7.25 类型通用数学 <tgmath.h> (p: TBD)
- F.10.4.5 平方根函数 (p: TBD)
- C11 标准 (ISO/IEC 9899:2011)
- 7.12.7.5 平方根函数 (p: 249)
- 7.25 类型通用数学 <tgmath.h> (p: 373-375)
- F.10.4.5 平方根函数 (p: 525)
- C99 标准 (ISO/IEC 9899:1999)
- 7.12.7.5 平方根函数 (p: 229-230)
- 7.22 类型通用数学 <tgmath.h> (p: 335-337)
- F.9.4.5 平方根函数 (p: 462)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.5.5.2 平方根函数
[编辑] 另请参阅
(C99)(C99) |
计算给定幂的数字 (xy) (函数) |
(C99)(C99)(C99) |
计算立方根 (3√x) (函数) |
(C99)(C99)(C99) |
计算两个给定数字的平方和的平方根(√x2 +y2 ) (函数) |
(C99)(C99)(C99) |
计算复平方根 (函数) |
C++ 文档,关于 sqrt
|