将 System.Double 与“0"(数字,整数?)进行比较的正确方法

The right way to compare a System.Double to #39;0#39; (a number, int?)(将 System.Double 与“0(数字,整数?)进行比较的正确方法)
本文介绍了将 System.Double 与“0"(数字,整数?)进行比较的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这可能是一个简单的愚蠢问题,但我需要知道才能确定.

Sorry, this might be a easy stupid question, but I need to know to be sure.

我有这个 if 表达式,

void Foo()
{
    System.Double something = GetSomething();
    if (something == 0) //Comparison of floating point numbers with equality 
                     // operator. Possible loss of precision while rounding value
        {}
}

这个表达式是否等于

void Foo()
{
    System.Double something = GetSomething();
    if (something < 1)
        {}
}

?因为那时我可能会遇到问题,例如输入 if值为 0.9.

? Because then I might have a problem, entering the if with e.g. a value of 0.9.

推荐答案

那么,你需要将值接近 0 吗?如果您执行大量无限精度"的浮点运算可能会导致 0,您最终可能会得到非常接近"0 的结果.

Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.

通常在这种情况下,您希望提供某种 epsilon,并检查结果是否在该 epsilon 内:

Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:

if (Math.Abs(something) < 0.001)

您应该使用的 epsilon 是特定于应用程序的 - 这取决于您在做什么.

The epsilon you should use is application-specific - it depends on what you're doing.

当然,如果结果应该完全为零,那么简单的相等检查就可以了.

Of course, if the result should be exactly zero, then a simple equality check is fine.

这篇关于将 System.Double 与“0"(数字,整数?)进行比较的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)