简体   繁体   English

双精度?

[英]Double precision?

I have a situation where I'm sending a number to a method, it divides that number into 6 and returns a List with the number 6 divided by n number of items. 我有一种情况,我正在向一个方法发送一个数字,它将该数字分成6并返回一个数字6除以n项目的List。 I'm pulling the dividing number from a dictionary.count and combining the returning list with the dictionary I pulled it from. 我正在从dictionary.count中提取分割数,并将返回的列表与我从中提取的字典组合起来。 Returned list, For some reason it does not always return the correct number of items. 返回列表,由于某种原因,它并不总是返回正确数量的项目。 It works fine through 12. But then it's predictable, if not reliable. 它在12阶段工作正常。但是如果不可靠的话,它是可预测的。 The following numbers return a list with 1 less index than is needed...13,15,18,23,25,20,27,28,30.....The code below was pulled from a larger project. 以下数字返回一个列表,其索引少于所需的索引... 13,15,18,23,25,20,27,28,30 .....下面的代码是从一个更大的项目中提取的。

public void DivTest()
{
    double value;
    Double.TryParse(textBox1.Text, out value);

    double div = 6 / value;
    int count = 1;

    StringBuilder sb = new StringBuilder();

    for (double d = div; d <= 6; d += div)
    {
        sb.Append(count.ToString()).Append("  :  ")
            .Append(d.ToString("0.0000")).Append("  :  ")                                                                                                                             
            .Append(div.ToString("0.0000")).AppendLine();

        count++;
    }

    label1.Text = sb.ToString();
}

If you add this code to a form with a default named textbox, label and button, it probably won't work correctly with you either. 如果您将此代码添加到具有默认命名文本框,标签和按钮的表单,则它可能无法正常使用。 The last line should always be 6, but it's with the numbers I've mentioned. 最后一行应该总是6,但它与我提到的数字一致。 I thought it was a rounding issue, but I'm not using rounding in this example. 我认为这是一个四舍五入的问题,但我不是在这个例子中使用舍入。 Any ideas? 有任何想法吗? Thanks. 谢谢。

It is a rounding problem, or rather a problem with the limited precision of numbers. 这是一个舍入问题,或者说是数字精度有限的问题。

The rounding occurs when you do the division. 进行舍入时会进行舍入。 The result can't be represented exactly, it's limited by the precision. 结果无法准确表示,受精度限制。

When the result is rounded up, you will end up with a slightly larger number when you add them up, for example 6.000000000000001 instead of 6. As that is larger than 6, it won't enter the last iteration in the loop. 当结果向上舍入时,添加它们时最终会有一个稍大的数字,例如6.000000000000001而不是6.当它大于6时,它将不会进入循环中的最后一次迭代。

You would fix this by using an integer variable for the loop, simply looping from 1 to value . 你可以通过使用循环的整数变量来解决这个问题,只需从1循环到value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM