精度损耗转换成多倍有多大? [英] How big is the precision loss converting long to double?

查看:101
本文介绍了精度损耗转换成多倍有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关于stackoverflow和C#文档的其他文章中读到,将long(或表示数字的任何其他数据类型)转换为double会失去精度.由于浮点数的表示,这一点很明显.

I have read in different post on stackoverflow and in the C# documentation, that converting long (or any other data type representing a number) to double loses precision. This is quite obvious due to the representation of floating point numbers.

我的问题是,如果将较大的数字转换为double,则精度损失有多大?我是否必须期望差异大于+/- X?

My question is, how big is the loss of precision if I convert a larger number to double? Do I have to expect differences larger than +/- X ?

我想知道的原因是,我必须处理一个连续的计数器,即long.此值由我的应用程序读取为string,需要进行强制转换,并且必须除以例如10或其他一些较小的数字,然后进行进一步处理.

The reason I would like to know this, is that I have to deal with a continuous counter which is a long. This value is read by my application as string, needs to be cast and has to be divided by e.g. 10 or some other small number and is then processed further.

decimal更适合此任务吗?

推荐答案

long(或表示数字的任何其他数据类型)转换为double会失去精度.由于浮点数的表示,这一点很明显.

converting long (or any other data type representing a number) to double loses precision. This is quite obvious due to the representation of floating point numbers.

这看起来似乎不太明显,因为精度损失取决于long的值.对于介于<2 52 和2 52 之间的值,根本没有精度损失.

This is less obvious than it seems, because precision loss depends on the value of long. For values between -252 and 252 there is no precision loss at all.

如果将较大的数字转换为双精度,则损失的精度有多大?我是否必须期望差异大于+/- X

How big is the loss of precision if I convert a larger number to double? Do I have to expect differences larger than +/- X

对于数量级大于2 52 的数字,您将遇到一些精度损失,具体取决于您超出52位限制的范围.如果long的绝对值适合58位,则精度损失的幅度将为58-52 = 6位,即+/- 64.

For numbers with magnitude above 252 you will experience some precision loss, depending on how much above the 52-bit limit you go. If the absolute value of your long fits in, say, 58 bits, then the magnitude of your precision loss will be 58-52=6 bits, or +/-64.

decimal更适合此任务吗?

Would decimal be more appropriate for this task?

decimaldouble具有不同的表示形式,并且使用了不同的基数.由于您打算将数字除以小数字",因此不同的表示形式会给您带来不同的划分误差.具体来说,double会更好地处理除以2(2、4、8、16等)的幂,因为这样的除法可以通过从指数中减去而无需触及尾数来完成.同样,大型decimal除以十,一百等时,也不会损失有效位数.

decimal has a different representation than double, and it uses a different base. Since you are planning to divide your number by "small numbers", different representations would give you different errors on division. Specifically, double will be better at handling division by powers of two (2, 4, 8, 16, etc.) because such division can be accomplished by subtracting from exponent, without touching the mantissa. Similarly, large decimals would suffer no loss of significant digits when divided by ten, hundred, etc.

这篇关于精度损耗转换成多倍有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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