从浮点数中删除小数部分但保留类型的有效方法

Efficient way to drop the fractional part from float but retain the type

本文关键字:类型 保留 有效 方法 浮点数 删除 小数部      更新时间:2023-10-16

我知道通过 std::round、std::floor 或 std::ceil 或简单的类型转换,我们可以删除小数部分,但使用类型转换,变量会丢失其原始类型(浮点数或双精度(。

有什么办法,我可以保留类型并仍然有效地删除小数部分。

我认为一种方法是从数字中减去小数部分,但这并不那么有效。那么,也许还有其他一些方法?

例-

float a = 123.456;
float b;
b = do something on a;

结果 b 为 123.0

例如,保留std::round原始类型:

float round(float arg);
double round(double arg);

对于std::floorstd::ceil也是如此。

加法。以下是一些基准测试结果。

编译器原始循环标准::ceil 标准:地板标准::trunc 标准::圆形 -------------------------------------------------------------------- 海湾合作委员会 8.36 8.20 8.19 8.21 32.95 GCC(F( 2.88 8.20 8.20 8.20 11.01 MSVS 8.20 28.47 31.90 67.14 97.84 msvs(f( 8.13 13.70 14.00 67.27 97.50

编译器:gcc 7.3.0msvs 2018 15.9.0,机器:Core i7-4770

法典。编译选项:

gcc: --std=c++17 -O3 -m64 -march=native -fno-tree-vectorize gcc(f(: --std=c++17 -O3 -m64 -march=native -ffast-math -fno-tree-vectorize msvs:/fp:precise/fp:except/O2/std:c++latest ... msvs(f(:/fp:fast/fp:except-/O2/std:c++latest ...

坦率地说,我认为这些结果本身(在绝对值中(不是很相关。使用快速数学选项,某些函数仅简化为单个汇编指令vroundss。应该分析实际代码以获得相关结果。

查看modf

#include <cmath>
float a = 123.456;
float b, c;
c = std::modf(a, &b);
// c = 0.456
// b = 123.0

如果不需要返回值(小数部分(,则不必使用它。

或(自 C++11 起(trunc

float b = std::trunc(a);