pra*_*pin 6 c++ floating-point rounding
在C和C++中,我们都知道将浮点值转换为整数会执行截断。这意味着,无论是对于C 风格的转换还是对于 C 风格的转换,都将修复为零static_cast。
static_assert(static_cast<int>(2.9) == 2);
static_assert((int)-3.7 == -3);
Run Code Online (Sandbox Code Playgroud)
要将浮点数转换为整数,有 4 个选项,每个选项都由以下标准函数实现<cmath>:
roundfloorceiltrunc我根据自己的经验,从最常用到最不常用的顺序排列了选项(这有点主观)。
向零截断意味着从 -0.999... 到 0.999... 的所有值都转换为 0。因此存在接近 0 的数学异常,这使得截断很少有用。我的印象是,几乎每次程序员直接将浮点转换为整数时,他实际上想要floor,但可以承受trunc行为,因为该值应该始终为正数。
我的问题是:选择第四个选项截断的动机是什么?我敢打赌这主要是历史性的,但是当 C 最初开发时,一定有一些充分的理由选择截断而不是更有用的舍入或下限。
小智 4
当您想要对值的模进行取底而不考虑符号时,可以使用它。发生这种情况的原因有多种,每个应用程序都有其特定的原因。你可能会在物理、金融、工程等领域拥有它。
在 x86_64 上,trunc(float)映射到roundssglibc 上的指令
ENTRY(__truncf_sse41)
roundss $11, %xmm0, %xmm0
ret
END(__truncf_sse41)
Run Code Online (Sandbox Code Playgroud)
上面的常量 $11,它是实际指令的立即操作数,并确定舍入特性。该特定指令包含您提到的选择(请参阅英特尔内部函数指南):
__m128 _mm_round_ss (__m128 a, __m128 b, int rounding)
Synopsis
__m128 _mm_round_ss (__m128 a, __m128 b, int rounding)
#include <smmintrin.h>
Instruction: roundss xmm, xmm, imm8
CPUID Flags: SSE4.1
Description
Round the lower single-precision (32-bit) floating-point element in b using the rounding parameter, store the result as a single-precision floating-point element in the lower element of dst, and copy the upper 3 packed elements from a to the upper elements of dst.
Rounding is done according to the rounding[3:0] parameter, which can be one of:
(_MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) // round to nearest, and suppress exceptions
(_MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) // round down, and suppress exceptions
(_MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) // round up, and suppress exceptions
(_MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) // truncate, and suppress exceptions
_MM_FROUND_CUR_DIRECTION // use MXCSR.RC; see _MM_SET_ROUNDING_MODE
Run Code Online (Sandbox Code Playgroud)
所以这绝不是一种语言选择,而是用户的需求。
| 归档时间: |
|
| 查看次数: |
1189 次 |
| 最近记录: |