四舍五入以用于int-& gt;浮动-& gt;int往返转换 [英] Rounding to use for int -> float -> int round trip conversion

查看:58
本文介绍了四舍五入以用于int-& gt;浮动-& gt;int往返转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为数据库引擎编写一组数字类型转换函数,并且我担心将较大的整数浮点值转换为具有更高精度的整数类型的行为.

例如,将32位int转换为32位单精度浮点数.浮点数的23位有效数字产生约7个十进制数字的精度,因此转换任何大于约7个数字的int都将导致精度损失(这是可以预期的).但是,当将这样的float转换回int时,最终会得到其二进制表示形式的低序数字伪像:

  #include< iostream>#include< iomanip>使用命名空间std;int main(){整数a = 2147483000;cout<<<<恩德尔浮点数f =(float)a;cout<<setprecision(10)<<f<<恩德尔int b =(int)f;cout<<b<<恩德尔返回0;} 

此打印:

  214748300021474830082147483008 

尾随008超出了浮点数的精度,因此似乎不希望保留在int中,因为在数据库应用程序中,用户主要关注十进制表示形式,而尾随0表示无效数字.

所以我的问题是:是否有任何知名的现有系统在float-> int(或double-> long long)转换中执行十进制有效数字舍入,并且有任何众所周知的有效算法来执行此操作?

(注意:我知道某些系统具有十进制浮点类型,例如解决方案

std :: numeric_limits< float> :: digits10 说,您只能获得6个浮点数.

为您的语言,处理器和数据分配选择一种有效的算法,以).然后减去 digits10 所说的精确数字位数,得出要剔除的数字位数.将其用作索引以查找10的幂以用作模数.等等.

一个关注点:假设您将浮点数转换为十进制数,然后执行这种舍入或截断操作.然后使用相同的舍入/截断方案将已调整"的十进制转换为浮点数,然后再转换回十进制.您得到相同的十进制值吗?希望是.

这并不是您真正要寻找的东西,但可能会很有趣: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 says you only get 6 precise digits for float.

Pick an efficient algorithm for your language, processor, and data distribution to calculate-the-decimal-length-of-an-integer (or here). Then subtract the number of digits that digits10 says are precise to get the number of digits to cull. Use that as an index to lookup a power of 10 to use as a modulus. Etc.

One concern: Let's say you convert a float to a decimal and perform this sort of rounding or truncation. Then convert that "adjusted" decimal to a float and back to a decimal with the same rounding/truncation scheme. Do you get the same decimal value? Hopefully yes.

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-&amp; gt;浮动-&amp; gt;int往返转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆