跳转到内容
新建笔记

C++ 数学函数:定义域、取整与浮点余数

使用数学函数时,除了名字,还需要确认头文件、实参类型、单位和定义域。下面保留原表全部函数,按 C++17 的接口整理;示例显式写 std::。C++17 <cmath>。

类别函数使用要点
绝对值abs、fabs<cmath> 提供浮点重载;整数 abs 还应保证结果可由返回类型表示
根、幂与指数sqrt、cbrt、pow、exp、exp2实数平方根通常要求输入非负;cbrt 可处理负数;pow 不是任意整数精确幂算法
对数log、log10、log2分别为自然、10 和 2 为底的对数;普通有限实数结果要求输入大于 0
三角函数sin、cos、tan输入为弧度;不要把角度值直接传入
反三角函数asin、acos、atan、atan2结果为弧度;asin/acos 的实数定义域是 −1~1;atan2(y, x) 参数顺序不能倒置
双曲与反双曲sinh、cosh、tanh、asinh、acosh、atanhacosh 的实数定义域为 x≥1;atanh 的普通有限实数定义域为 −1<x<1
取整floor、ceil、trunc、round分别向负无穷、正无穷、零取整;round 的中点远离零;返回值仍可为浮点类型
浮点余数fmod、remainder两者使用不同的商取整规则,不能互换;除数应非零
分离整数与小数modf通过指针写出整数部分,返回小数部分;不是通用的类型转换函数
C 风格伪随机数rand、srand位于 <cstdlib>;分别生成值和设置种子,fabs/modf 不属于这一类

fmod(x, y) 按向零截断的商取余;remainder(x, y) 按最近整数的商取余,商刚好处于中点时取偶数。因此 fmod(7, 4) 为 3,而 remainder(7, 4) 为 −1。C++ 的 % 是整数余数运算符,不直接用于 double。

浮点数学错误可能通过返回值、errno 或浮点异常标志表达,取决于函数和实现支持,不能统一假定会抛出 C++ 异常。应按输入范围选择算法,并查看实现的 math_errhandling。下面只调用定义域内的输入;没有靠无效输入或溢出来演示“结果”。

示例覆盖原表中的全部函数。近似结果使用容差比较;所选二进制可精确表示的简单结果才直接比较相等。这里的固定绝对容差用于这些有限小数值,不是任意尺度数据的通用误差策略。

math-functions.cpp
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <iostream>
bool close(double actual, double expected) {
return std::abs(actual - expected) < 1e-12;
}
int main() {
const double pi = std::acos(-1.0);
assert(std::abs(-7) == 7 && std::fabs(-2.5) == 2.5);
assert(close(std::sqrt(9.0), 3.0));
assert(close(std::cbrt(-8.0), -2.0));
assert(close(std::pow(2.0, 3.0), 8.0));
assert(close(std::exp(0.0), 1.0) && close(std::exp2(3.0), 8.0));
assert(close(std::log(std::exp(1.0)), 1.0));
assert(close(std::log10(100.0), 2.0) && close(std::log2(8.0), 3.0));
assert(close(std::sin(pi / 2.0), 1.0) && close(std::cos(0.0), 1.0));
assert(close(std::tan(pi / 4.0), 1.0));
assert(close(std::asin(0.5), pi / 6.0));
assert(close(std::acos(0.5), pi / 3.0));
assert(close(std::atan(1.0), pi / 4.0));
assert(close(std::atan2(1.0, 0.0), pi / 2.0));
assert(close(std::sinh(0.0), 0.0) && close(std::cosh(0.0), 1.0));
assert(close(std::tanh(0.0), 0.0));
assert(close(std::asinh(std::sinh(0.5)), 0.5));
assert(close(std::acosh(std::cosh(0.5)), 0.5));
assert(close(std::atanh(std::tanh(0.5)), 0.5));
assert(std::floor(-2.7) == -3.0);
assert(std::ceil(-2.7) == -2.0);
assert(std::trunc(-2.7) == -2.0);
assert(std::round(-2.5) == -3.0 && std::round(2.5) == 3.0);
assert(std::fmod(7.0, 4.0) == 3.0);
assert(std::remainder(7.0, 4.0) == -1.0);
assert(std::fmod(-7.0, 4.0) == -3.0);
assert(std::remainder(-7.0, 4.0) == 1.0);
double integral = 0.0;
const double fractional = std::modf(-3.25, &integral);
assert(integral == -3.0 && fractional == -0.25);
std::srand(123);
const int first = std::rand();
std::srand(123);
assert(std::rand() == first); // 同一实现中,同种子重现序列
assert(first >= 0 && first <= RAND_MAX);
std::cout << "math OK; fmod=3; remainder=-1; split=-3,-0.25\n";
}

srand 不必在每次获取随机数前调用;重复播种会重复启动序列。同一个种子不保证不同标准库产生同一组 rand 值。新代码需要明确分布时,可使用 <random> 中的引擎与分布,保留 rand/srand 主要是为了读懂已有代码。C 风格随机数接口。