Log
定义于头文件 <cmath>
中。
描述
计算 `num` 的自然(以 `e` 为底)对数。
该库为所有 cv-不限定浮点类型提供了 `std::log` 的重载,作为参数 `num` 的类型。
声明
- C++23
- C++11
// 1)
/* floating-point-type */ log( /* floating-point-type */ num );
// 2)
float logf( float num );
// 3)
long double logl( long double num );
// 4)
template< class Integer >
double log ( Integer num );
// 1)
float log ( float num );
// 2)
double log ( double num );
// 3)
long double log ( long double num );
// 4)
float logf( float num );
// 5)
long double logl( long double num );
// 6)
template< class Integer >
double log ( Integer num );
参数
num
- 浮点或整数值
返回值
如果没有发生错误,返回 `num` 的自然(以 `e` 为底)对数(ln(num) 或 loge(num))。
如果发生域错误,返回一个实现定义的值(如果支持,为 NaN)。
如果发生极点错误,则返回-HUGE_VAL
、-HUGE_VALF
或-HUGE_VALL
。
错误处理
错误按 math_errhandling 中指定的方式报告。
如果 num
小于零,则发生域错误。
如果 num
为零,则可能发生极点错误。
如果实现支持 IEEE 浮点运算(IEC 60559),
如果参数是 `±0`,返回 `-∞` 并引发 `FE_DIVBYZERO`。如果参数是 `1`,返回 `+0`。如果参数是负数,返回 NaN 并引发 `FE_INVALID`。如果参数是 `+∞`,返回 `+∞`。如果参数是 NaN,返回 NaN。
备注
额外的重载不需要完全按照额外重载提供。它们只需要足以确保对于其整数类型的参数 num
,
std::log(num)
的效果与 std::log(static_cast<double>(num))
相同。
示例
#include <cerrno>
#include <cfenv>
#include <cstring>
#include <cmath>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "log(1) = " << std::log(1) << '\n'
<< "base-5 logarithm of 125 = " << std::log(125)/std::log(5) << '\n';
// special values
std::cout << "log(1) = " << std::log(1) << '\n'
<< "log(+Inf) = " << std::log(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "log(0) = " << std::log(0) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
log(1) = 0
base-5 logarithm of 125 = 3
log(1) = 0
log(+Inf) = inf
log(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised