我处于需要将 0.5 和 -0.5 舍入为 0 的情况。所以我检查了各种文档 -
通用 C++ 方法似乎总是与 0 相差 0.5。
https://en.cppreference.com/w/cpp/numeric/math/round
如果我通过设置舍入样式来采用较低级别的方法,这似乎是一种非常全局的方法,并且可能具有线程和 CPU 状态含义,这非常烦人。
https://en.cppreference.com/w/cpp/types/numeric_limits/float_round_style
有没有一种轻量级、stl、简单的方法实现向下舍入到0?
#include <cmath>
template <typename T>
T absmax(T a, T b)
{
return std::abs(a) > std::abs(b) ? a : b;
}
template <typename T>
T round_towards_zero(T x)
{
return absmax(std::round(std::nextafter(x, T(0))), std::trunc(x));
}
对于足够小的数字,您不需要
absmax(..., trunc(x))
。如果没有它,我就会开始得到 double
左右以及更大的 1e16
的错误答案。