使用 -eq/-ne 比较两个"Double"变量不会验证数字的创建者是否超过 2 位



我试图比较Powershell中的两个Double变量。当变量超过2位(不计算精度)时,相等性测试意外失败。

我错过了什么明显的东西吗?

下面是测试脚本的输出:
PS C:test> .test.ps1
==========
TEST ONE
==========
Value of Double1: 336.1
Type of Double1: System.Double
-----
Value of Double2: 336.2
Type of Double2: System.Double
-----
Value of Double1+.1: 336.2
Type of Double1+.1: System.Double
-----
Does Double1 not equal Double2: True
Does Double1+.1 not equal Double2: True
==========
TEST TWO
==========
Value of Double3: 36.1
Type of Double3: System.Double
-----
Value of Double4: 36.2
Type of Double4: System.Double
-----
Value of Double3+.1: 36.2
Type of Double3+.1: System.Double
-----
Does Double3 not equal Double4: True
Does Double3+.1 not equal Double4: False

这里是测试脚本,注意到第一个测试失败了,我在变量中添加了。1,但是第二个测试通过了。

##################################
# START TEST
##################################
$Double1 = 336.1
$Double2 = 336.2
write-host "=========="
write-host "TEST ONE"
write-host "=========="
write-host "Value of Double1: $Double1"
write-host "Type of Double1:" $Double1.GetType().FullName
write-host "-----"
write-host "Value of Double2: $Double2"
write-host "Type of Double2:" $Double2.GetType().FullName
write-host "-----"
write-host "Value of Double1+.1:" ($Double1+.1)
write-host "-----"
write-host "Does Double1 not equal Double2:" ($Double1 -ne $Double2)    
write-host "Does Double1+.1 not equal Double2:" (($Double1+.1) -ne $Double2)
write-host ""
write-host "=========="
write-host "TEST TWO"
write-host "=========="
$Double3 = 36.1
$Double4 = 36.2
write-host ""
write-host "Value of Double3: $Double3"
write-host "Type of Double3:" $Double3.GetType().FullName
write-host "-----"
write-host "Value of Double4: $Double4"
write-host "Type of Double4:" $Double4.GetType().FullName
write-host "-----"
write-host "Value of Double3+.1:" ($Double3+.1)
write-host "-----"
write-host "Does Double3 not equal Double4:" ($Double3 -ne $Double4)    
write-host "Does Double3+.1 not equal Double4:" (($Double3+.1) -ne $Double4)
write-host ""

请注意,这不是Powershell的问题,这只是浮点运算存在的问题。你可以在c#

中重现相同的行为
double d = 336.1;
Console.WriteLine((d + .1) == 336.2); // False

问题在于336.1 + .1实际上并不等于336.2。您可以通过转储

两个值的原始字节来证明这一点
 unsafe
 {
    double d1 = 336.1;
    double d2 = d + .1d;
    double d3 = 336.2;
    Console.WriteLine(*(long*)(&d2));
    Console.WriteLine(*(long*)(&d3));
 }

打印

4644622109139743540
4644622109139743539

请注意,最后2个字节的值相差1。至于为什么会出现这种情况,更多地处理浮点运算的人会说。一般来说,在比较浮点值时应该小心。与其严格相等,不如检查它们是否在特定范围内

if (Math.Abs(d2 - d3) <= .01)) {
  ...
}

尝试将变量类型转换为[System]。小数)如何正确比较双打在powershell?http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

相关内容

  • 没有找到相关文章

最新更新