如何使用Doubles检测精度的总损失? [英] How do I detect total loss of precision with Doubles?

查看:125
本文介绍了如何使用Doubles检测精度的总损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码时,两行都显示0:

When I run the following code, I get 0 printed on both lines:

Double a = 9.88131291682493E-324;
Double b = a*0.1D;
Console.WriteLine(b);
Console.WriteLine(BitConverter.DoubleToInt64Bits(b));

如果操作结果超出范围,我希望得到Double.NaN.取而代之的是,我得到0.看来要能够检测出何时发生这种情况,我必须检查一下:

I would expect to get Double.NaN if an operation result gets out of range. Instead I get 0. It looks that to be able to detect when this happens I have to check:

  • 在操作之前,请检查是否有任何操作数为零
  • 运算后,如果两个操作数都不为零,请检查结果是否为零.如果没有让它运行.如果为零,则将Double.NaN分配给它,以表示它实际上不是零,这只是一个结果,无法在此变量中表示.

那太笨拙了.有没有更好的办法? Double.NaN的用途是什么?我假设某些操作必须返回它,当然设计人员没有将它放在那里以防万一?这可能是BCL中的错误吗? (我知道不太可能,但这就是为什么我想了解Double.NaN应该如何工作的原因)

That's rather unwieldy. Is there a better way? What Double.NaN is designed for? I'm assuming some operations must have return it, surely designers did not put it there just in case? Is it possible that this is a bug in BCL? (I know unlikely, but, that's why I'd like to understand how that Double.NaN is supposed to work)

更新

顺便说一句,此问题不是特定于double的.小数点会完全相同:

By the way, this problem is not specific for double. decimal exposes it all the same:

Decimal a = 0.0000000000000000000000000001m;
Decimal b =  a* 0.1m;
Console.WriteLine(b);

这也为零.

在我的情况下,我需要加倍,因为我需要它们提供的范围(我正在研究概率计算),而我并不担心精度.

In my case I need double, because I need the range they provide (I'm working on probabilistic calculations) and I'm not that worried about precision.

尽管,我需要的是能够检测到何时我的结果停止,这意味着什么,即当计算将值降低到如此之低以至于不能再用double表示时.

What I need though is to be able to detect when my results stop mean anything, that is when calculations drop the value so low, that it can no longer be presented by double.

有检测这种情况的实用方法吗?

Is there a practical way of detecting this?

推荐答案

您需要的只是epsilon.

这是一个小数字",足够小,因此您不再对此感兴趣.

This is a "small number" which is small enough so you're no longer interested in.

您可以使用:

double epsilon = 1E-50;

并且只要您的因素之一变得比Epislon小,您就采取行动(例如,将其视为0.0)

and whenever one of your factors gets smaller than epislon you take action (for example treat it like 0.0)

这篇关于如何使用Doubles检测精度的总损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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