如何 std::round 加倍,但在中途情况下舍入为零?

问题描述 投票:0回答:1

我处于需要将 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

是否有一个轻量级的标准库和简单的方法来实现向下舍入到0?

c++ floating-point std rounding
1个回答
3
投票
#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
的错误答案。

© www.soinside.com 2019 - 2024. All rights reserved.