IronPython/C#浮点数据比较 [英] IronPython/C# Float data comparison

查看:72
本文介绍了IronPython/C#浮点数据比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有使用Prism Framework的基于WPF的应用程序.我们已经嵌入了IronPython并使用Python单元测试框架来自动化我们的应用程序GUI测试.

We have WPF based application using Prism Framework. We have embedded IronPython and using Python Unit Test framework to automate our application GUI testing.

效果很好.我们很难比较两个浮点数.

It works very well. We have difficulties in comparing two float numbers.

示例 C#

class MyClass
{
   public object Value { get; set;}
   public MyClass()
   {
        Value = (float) 12.345;
   } 
}

在IronPython中,当我将MyClass实例的Value属性与python float值(12.345)进行比较时,它表示不相等

In IronPython When I compare the MyClass Instance's Value property with python float value(12.345), it says it doesn't equal

Python 语句引发断言错误

self.assertEqual(myClassInstance.Value, 12.345)

Python 语句工作正常.

self.assertEqual(float(myClassInstance.Value.ToString()), 12.345) 

当我检查type(myClassInstance.Value)的类型时,它在Python中返回Single,而type(12.345)返回float.如何在不进行显式转换的情况下处理C#与Python的浮点数比较?

When I check the type of the type(myClassInstance.Value), it returns Single in Python where as type(12.345) returns float. How to handle the C# float to Python comparison without explicit conversions?

推荐答案

我不熟悉Python,但根据对CLR和C#的了解,我正在回答一个问题.

I'm not familiar with Python but I'm taking a stab at an answer based on what I know about the CLR and C#.

在您的示例中,将float值分配给Value属性时,将其装箱".装箱是一种在对象类型的变量中存储值类型(例如float,int等)的方法.如果assert方法采用两个对象参数,则可能正在执行引用相等,在这种情况下,这两个对象将不是相等"的.您需要拆箱" Value属性以获得值比较.在C#中,只需将对象类型的变量转换回其原始类型即可.

In your example, the float value is "boxed" when it's assigned to the Value property. Boxing is a way of storing a value type (such as a float, int, etc) in an object-typed variable. If the assert method takes two object parameters, it might be doing reference equality in which case the two would not be "equal". You would need to "unbox" the Value property to get a value comparison. In C# this is done by simply casting the object-typed variable back to its original type.

要演示,请参见以下代码.请注意,它的第一个打印为False,第二个打印为True.

To demonstrate, see the following code. Note that it prints False for the first and True for the second.

void Main()
{
    object value1 = 1234.5F;
    object value2 = 1234.5F;
    Console.WriteLine(AreEqual(value1, value2));
    Console.WriteLine(AreEqual((float)value1, (float)value2));
}

bool AreEqual(object value1, object value2) {
    return value1 == value2;
}

bool AreEqual(float value1, float value2) {
    return value1 == value2;
}

但是,我必须同意伊格纳西奥(Ignacio)的观点,即永远不应该比较两个浮点数是否相等.您应该始终使用包含公差的方法,因为浮点运算有时会导致微小的差异.

However, I have to agree with Ignacio that you should never compare two floating point numbers for equality. You should always use a method that includes a tolerance since floating point operations can sometimes result in tiny differences.

这篇关于IronPython/C#浮点数据比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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