.NET 上的双精度问题 [英] Double precision problems on .NET

查看:24
本文介绍了.NET 上的双精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 C# 函数:

I have a simple C# function:

public static double Floor(double value, double step)
{
    return Math.Floor(value / step) * step;
}

即计算较高的数,小于或等于value",即step"的倍数.但它缺乏精确度,如以下测试所示:

That calculates the higher number, lower than or equal to "value", that is multiple of "step". But it lacks precision, as seen in the following tests:

[TestMethod()]
public void FloorTest()
{
    int decimals = 6;
    double value = 5F;
    double step = 2F;
    double expected = 4F;
    double actual = Class.Floor(value, step);
    Assert.AreEqual(expected, actual);
    value = -11.5F;
    step = 1.1F;
    expected = -12.1F;
    actual = Class.Floor(value, step);
    Assert.AreEqual(Math.Round(expected, decimals),Math.Round(actual, decimals));
    Assert.AreEqual(expected, actual);
}

第一个和第二个断言没问题,但第三个断言失败,因为结果只等于小数点后第 6 位.这是为什么?有什么办法可以纠正吗?

The first and second asserts are ok, but the third fails, because the result is only equal until the 6th decimal place. Why is that? Is there any way to correct this?

更新 如果我调试测试,我会看到这些值直到小数点后第 8 位而不是第 6 位才相等,这可能是因为 Math.Round 引入了一些不精确性.

Update If I debug the test I see that the values are equal until the 8th decimal place instead of the 6th, maybe because Math.Round introduces some imprecision.

注意在我的测试代码中,我写了F"后缀(显式浮点常量),其中我的意思是D"(双精度),所以如果我改变它,我可以获得更高的精度.

Note In my test code I wrote the "F" suffix (explicit float constant) where I meant "D" (double), so if I change that I can have more precision.

推荐答案

如果省略所有 F 后缀(即 -12.1 而不是 -12.1F)得到更多的平等.由于 F,您的常量(尤其是预期值)现在是浮点数.如果您是故意这样做的,请解释一下.

If you omit all the F postfixes (ie -12.1 instead of -12.1F) you will get equality to a few digits more. Your constants (and especially the expected values) are now floats because of the F. If you are doing that on purpose then please explain.

但对于其余的我同意其他关于比较双精度或浮点值是否相等的答案,它只是不可靠.

But for the rest i concur with the other answers on comparing double or float values for equality, it's just not reliable.

这篇关于.NET 上的双精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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