std::sqrt, std::sqrtf, std::sqrtl
定义于头文件
<cmath>
|
||
(1) | ||
float sqrt ( float arg );
|
||
float sqrtf( float arg );
|
(C++11 起) | |
double sqrt ( double arg );
|
(2) | |
(3) | ||
long double sqrt ( long double arg );
|
||
long double sqrtl( long double arg );
|
(C++11 起) | |
double sqrt ( IntegralType arg );
|
(4) | (C++11 起) |
1-3) 计算
arg
的平方根。
4) 接受任何整数类型参数的重载集或函数模模板。等价于 (2) (将参数转型为 double )。
参数
arg | - | 浮点或整数类型值 |
返回值
若不出现错误,则返回 arg
的平方根( √argarg )。
若出现定义域错误,则返回实现定义值(支持的平台上为 NaN )。
若出现下溢所致的值域错误,则返回(舍入后的)正确结果。
错误处理
报告 math_errhandling 中指定的错误。
若 arg
小于零则出现定义域错误。
若实现支持 IEEE 浮点算术( IEC 60559 ),则
- 若参数小于 -0 ,则引发 FE_INVALID 并返回 NaN 。
- 若参数为 +∞ 或 ±0 ,则返回不修改的参数。
- 若参数为 NaN ,则返回 NaN 。
注解
IEEE 标准要求 std::sqrt
为准确。其他要求为准确的运算只有算术运算符和函数 std::fma 。舍入到返回类型后(用默认舍入模式), std::sqrt
的结果与无限精度结果不可辨别。换言之,误差小于 0.5 ulp 。其他函数,含 std::pow ,不受这种制约。
示例
运行此代码
#include <iostream>
#include <cmath> #include <cerrno> #include <cfenv> #include <cstring> #pragma STDC FENV_ACCESS ON int main() { // 正常使用 std::cout << "sqrt(100) = " << std::sqrt(100) << '\n' << "sqrt(2) = " << std::sqrt(2) << '\n' << "golden ratio = " << (1+std::sqrt(5))/2 << '\n'; // 特殊值 std::cout << "sqrt(-0) = " << std::sqrt(-0.0) << '\n'; // 错误处理 errno = 0; std::feclearexcept(FE_ALL_EXCEPT); std::cout << "sqrt(-1.0) = " << std::sqrt(-1) << '\n'; if(errno == EDOM) std::cout << " errno = EDOM " << std::strerror(errno) << '\n'; if(std::fetestexcept(FE_INVALID)) std::cout << " FE_INVALID raised\n"; }
可能的输出:
sqrt(100) = 10 sqrt(2) = 1.41421 golden ratio = 1.61803 sqrt(-0) = -0 sqrt(-1.0) = -nan errno = EDOM Numerical argument out of domain FE_INVALID raised
参阅
(C++11)(C++11)
|
求某数的给定次幂( xyxy ) (函数) |
(C++11)(C++11)(C++11)
|
计算立方根( 3√xx3 ) (函数) |
(C++11)(C++11)(C++11)
|
计算两个给定数的平方和的平方根( √x2+y2x2+y2 ) (函数) |
右半平面范围中的复平方根 (函数模板) |
|
应用函数 std::sqrt 到 valarray 的每个元素 (函数模板) |
|
sqrt 的 C 文档
|