C# Compare two double with .Equals()(C# 用 .Equals() 比较两个双精度)
问题描述
我使用 ReShaper,当我用 == 比较两个双精度值时,它建议我应该使用 Math.具有公差的 ABS 方法.请参阅:https://www.jetbrains.com/help/resharper/2016.2/CompareOfFloatsByEqualityOperator.html
I use ReShaper and when I compare two double values with ==, it suggests that I should use the Math. ABS method with a tolerance. See: https://www.jetbrains.com/help/resharper/2016.2/CompareOfFloatsByEqualityOperator.html
这个例子
double d = 0.0;
double d2 = 0.0;
if (d == d2)
{
/* some code */
}
然后转换为
double d = 0.0;
double d2 = 0.0;
if (Math.Abs(d - d2) < TOLERANCE)
{
/* some code */
}
但我认为,对于开发人员来说,考虑正确的容差确实很复杂.所以我认为这可能在 Double.Equals() 方法中实现.
But I think it's really complicated for a developer to think about the right tolerance. So I thought this may be implemented in the Double.Equals() method.
但是这个方法是这样实现的
But this method is implemented like so
public override bool Equals(Object obj) {
if (!(obj is Double)) {
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
if (temp == m_value) {
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
public bool Equals(Double obj)
{
if (obj == m_value) {
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
这是为什么呢?比较双精度值的正确方法是什么?
推荐答案
你可以创建一个扩展方法
You could create an extension method
public static class DoubleExtension
{
public static bool AlmostEqualTo(this double value1, double value2)
{
return Math.Abs(value1 - value2) < 0.0000001;
}
}
并像这样使用它
doubleValue.AlmostEqualTo(doubleValue2)
这篇关于C# 用 .Equals() 比较两个双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 用 .Equals() 比较两个双精度
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
