std::sqrt, std::sqrtf, std::sqrtl
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| 在标头 <cmath> 定义
|
||
| (1) | ||
float sqrt ( float num ); double sqrt ( double num ); long double sqrt ( long double num ); |
(C++23 前) | |
/* 浮点数类型 */ sqrt ( /* 浮点数类型 */ num ); |
(C++23 起) (C++26 起 constexpr) |
|
float sqrtf( float num ); |
(2) | (C++11 起) (C++26 起为 constexpr) |
long double sqrtl( long double num ); |
(3) | (C++11 起) (C++26 起为 constexpr) |
| SIMD 重载 (C++26 起) |
||
| 在标头 <simd> 定义
|
||
template< /*math-floating-point*/ V > constexpr /*deduced-simd-t*/<V> sqrt ( const V& v_num ); |
(S) | (C++26 起) |
| 额外重载 (C++11 起) |
||
| 在标头 <cmath> 定义
|
||
template< class Integer > double sqrt ( Integer num ); |
(A) | (C++26 起为 constexpr) |
1-3) 计算
num 的平方根。标准库提供所有以无 cv 限定的浮点数类型作为形参的类型的 std::sqrt 重载。(C++23 起)|
S) SIMD 重载对
v_num 实施逐元素 std::sqrt。
|
(C++26 起) |
|
A) 为所有整数类型提供额外重载,将它们当做
double。 |
(C++11 起) |
参数
| num | - | 浮点数或整数 |
返回值
如果没有发生错误,那么返回 num 的平方根(√num)。
如果发生定义域错误,那么返回值由实现定义(在支持的平台上是 NaN)。
如果发生下溢导致的值域错误,那么返回(舍入后的)正确结果。
错误处理
报告 math_errhandling 中指定的错误。
如果 num 小于零,那么发生定义域错误。
如果实现支持 IEEE 浮点数算术(IEC 60559),那么
- 如果实参小于 -0,那么引发 FE_INVALID 并返回 NaN。
- 如果实参是 +∞ 或 ±0,那么返回不修改的该值。
- 如果实参是 NaN,那么返回 NaN。
注解
IEEE 标准要求 std::sqrt 从无限精确的结果舍入。特别是在浮点数类型能表示精确结果时一定会产生精确结果。其他有此要求的运算只有算术运算符和函数 std::fma。其他函数,包括 std::pow,都没有受到这么强的制约。
额外重载不需要以 (A) 的形式提供。它们只需要能够对它们的整数类型实参 num 确保 std::sqrt(num) 和 std::sqrt(static_cast<double>(num)) 的效果相同。
示例
运行此代码
#include <cerrno>
#include <cfenv>
#include <cmath>
#include <cstring>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
int main()
{
// 正常使用
std::cout << "sqrt(100) = " << std::sqrt(100) << '\n'
<< "sqrt(2) = " << std::sqrt(2) << '\n'
<< "黄金比例 = " << (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\n";
}
可能的输出:
sqrt(100) = 10
sqrt(2) = 1.41421
黄金比例 = 1.61803
sqrt(-0) = -0
sqrt(-1.0) = -nan
errno = EDOM Numerical argument out of domain
发生 FE_INVALID
参阅
(C++11)(C++11) |
求某数的给定次幂(xy) (函数) |
(C++11)(C++11)(C++11) |
计算立方根(3√x) (函数) |
(C++11)(C++11)(C++11) |
计算斜边(弦)长 √x2 +y2 与 √x2 +y2 +z2 (C++17 起) (函数) |
| 右半平面范围中的复平方根 (函数模板) | |
| 应用函数 std::sqrt 到 valarray 的每个元素 (函数模板) | |
sqrt 的 C 文档
| |