std::sqrt, std::sqrtf, std::sqrtl
來自 cppreference.com
定義於標頭檔案 <cmath> |
||
(1) | ||
float sqrt ( float num ); double sqrt ( 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< /*數學浮點型別*/ V > constexpr /*推導 SIMD 型別*/<V> |
(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 時返回 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() { // normal use std::cout << "sqrt(100) = " << std::sqrt(100) << '\n' << "sqrt(2) = " << std::sqrt(2) << '\n' << "golden ratio = " << (1 + std::sqrt(5)) / 2 << '\n'; // special values std::cout << "sqrt(-0) = " << std::sqrt(-0.0) << '\n'; // error handling 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) |
將數字提升到給定冪(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 的每個元素 (函式模板) | |
C 文件 用於 sqrt
|