c# - Visual Studio 2015 Update 2 让浮点计算更准确?

标签 c# visual-studio-2015

我在 xUnit 中有以下测试用例。

Assert.NotEqual(0f, 0.1f + 0.2f - 0.3f);
Assert.NotEqual(0d, 0.1d + 0.2d - 0.3d);
Assert.Equal(0m, 0.1m + 0.2m - 0.3m);

多年来,他们在 .NET 4 或 4.5 上的 VS 2010、2012、2013 和 2015 中一直运行良好。结果与 MS 测试相同。测试用例是为了证明 float 计算可能不够精确。因为 0.1+0.2 预计为 0.30000000000000004。

然而,今天,我发现第一种情况被打破了,显然.NET运行时和编译器认为0.1f+0.2f==0.3f。我不确定这是否与我几天前升级到 VS 2015 Update 2 有关。然后我在 VS 2012 Update 4 中尝试相同的测试,第一个测试用例没问题。我怀疑 VS 2015 更新 2 的 .NET 编译器已损坏或正在使浮点计算更准确。只要由 VS 2015 update 2 编译,.NET 4、4.5 和 4.6.1 的结果是一致的。我不完全确定这是 VS 2015 update 2 的错误,还是好事?你有什么想法吗?

最佳答案

感谢乔恩、汉斯和霍根。同意这可能是编译器问题,因为我在 20 多年前编写了一个编译器。我已经按照建议在 https://github.com/dotnet/roslyn/issues/11311 报告了这个问题。使用以下测试用例。

    [TestMethod]
    public void TestFloatConst()
    {
        Assert.AreNotEqual(0f, 0.1f + 0.2f - 0.3f);//Broken in VS 2015 Update 2
    }

    [TestMethod]
    public void TestFloatConstComparison()
    {
        Assert.AreNotEqual(0.3f, 0.1f + 0.2f);//Broken in VS 2015 Update 2
    }

    [TestMethod]
    public void TestDoubleConst()
    {
        Assert.AreNotEqual(0d, 0.1d + 0.2d - 0.3d);
    }

    [TestMethod]
    public void TestDoubleConstComparison()
    {
        Assert.AreNotEqual(0.3d, 0.1d + 0.2d);
    }

    [TestMethod]
    public void TestDecimalConst()
    {
        Assert.AreEqual(0m, 0.1m + 0.2m - 0.3m);
    }

    [TestMethod]
    public void TestFloatVariable()
    {
        var a = 0.1f;
        var b = 0.2f;
        var c = 0.3f;
        Assert.AreNotEqual(0f, a+b-c);//OK in both debug and release builds
    }

关于c# - Visual Studio 2015 Update 2 让浮点计算更准确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226563/

相关文章:

c# - 从 MVC 6/Web Api Controller 返回错误字符串

c# - DataGridView 大小超出 splitContainer 面板,即使 Dock 属性为 Fill

c# - 如何在 Visual Studio 2015 RC 的一个解决方案中使用其他项目 DLL

c# - 具有 int 值的公共(public)枚举

c# - 绑定(bind)列表到 GridView

c# - 在 Visual Studio 2015 中创建插件

tfs - 如何让 TFS 忽略具有特定名称的所有文件夹

nested - 无法使用 Web Compiler 2015 编译嵌套的 less 文件

visual-studio - Visual Studio 中的事件选项卡向左移动?

c# - 当垃圾收集器在堆中移动数据时,引用是否会更新?