问题描述
我为数据库引擎编写一组数字类型转换函数,我担心将大型积分浮点值转换为整数类型的行为更精确。
I'm writing a set of numeric type conversion functions for a database engine, and I'm concerned about the behavior of converting large integral floating-point values to integer types with greater precision.
例如将32位int转换为32位单精度浮点数。浮点的23位有效位数产生大约7个精度的十进制数字,因此转换任何int大于大约7位数将导致精度损失(这是精细和预期)。但是,当你把这样一个float转换为int,你会得到它的二进制表示形式的工件的低位数:
Take for example converting a 32-bit int to a 32-bit single-precision float. The 23-bit significand of the float yields about 7 decimal digits of precision, so converting any int with more than about 7 digits will result in a loss of precision (which is fine and expected). However, when you convert such a float back to an int, you end up with artifacts of its binary representation in the low-order digits:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a = 2147483000;
cout << a << endl;
float f = (float)a;
cout << setprecision(10) << f << endl;
int b = (int)f;
cout << b << endl;
return 0;
}
打印:
2147483000
2147483008
2147483008
尾部008超出了浮点的精度,因此在int中保留似乎不受欢迎,因为在数据库应用程序中,用户主要关注十进制表示,尾随0用于表示无效数字。
The trailing 008 is beyond the precision of the float, and therefore seems undesirable to retain in the int, since in a database application, users are primarily concerned with decimal representation, and trailing 0's are used to indicate insignificant digits.
所以我的问题是:有没有任何知名的现有系统,执行十进制有效数字舍入在float - > int(或双 - 长long)转换,并有任何好(注意:我知道一些系统具有十进制浮点类型,例如由。然而,他们没有主流硬件支持,并且没有内置C / C ++。我可能想支持他们在路上,但我仍然需要直观地处理二进制浮点。)
(Note: I'm aware that some systems have decimal floating-point types, such as those defined by IEEE 754-2008. However, they don't have mainstream hardware support and aren't built into C/C++. I might want to support them down the road, but I still need to handle binary floats intuitively.)
推荐答案
std :: numeric_limits< float> :: digits10
表示您只能获取6个精确的浮点数字。
std::numeric_limits<float>::digits10
says you only get 6 precise digits for float.
高效的算法为您的语言,处理器和数据分配到(或
This isn't really what you're looking for but may be interesting reading: A Proposal to add a max significant decimal digits value to the C++ Standard Library Numeric limits
这篇关于舍入以使用int - > float - > int往返转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!