c# - C# 中的 Double Type 精度不是 15 位吗?

标签 c# types precision

我正在测试来自 Brainteasers: 的这段代码

        double d1 = 1.000001;

        double d2 = 0.000001;

        Console.WriteLine((d1 - d2) == 1.0);

结果是“假”。当我更改数据类型时:

        decimal d1 = 1.000001M;

        decimal d2 = 0.000001M;

        decimal d3 = d1-d2;

        Console.WriteLine(d3 == 1);

程序写下正确答案:“正确”。

这道题只用了 float 后的6位。 15 位精度发生了什么?

最佳答案

这与精度无关 - 它与代表性舍入误差有关。

System.Decimal 能够表示大的 float ,并显着降低出现您所看到的任何舍入错误的风险。 System.SingleSystem.Double 无法做到这一点,它们会将这些数字四舍五入并产生类似于您在示例中看到的问题。

System.Decimal 使用比例因子来保持小数位的位置,从而允许精确表示给定的 float ,而 System.SingleSystem.Double 只会尽可能接近您的值。

更多信息,请参阅System.Double :

Remember that a floating-point number can only approximate a decimal number, and that the precision of a floating-point number determines how accurately that number approximates a decimal number. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. The precision of a floating-point number has several consequences:

  • Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different.

  • A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

关于c# - C# 中的 Double Type 精度不是 15 位吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1395692/

相关文章:

c# - 如何将隐藏的输入传递给 C# 中的另一个程序

c# - 如何以编程方式设置应用程序池空闲超时?

合并程序集中的 .NET 类型定义 (ILMerge)

c++ - std::stringstream 中双输出的默认格式标志(和宽度)是什么?

c# - 如何在 C# 中的 Windows 窗体上设置波斯日历

c# - 如何在 C# 中将 t-sql 的 "tinyint"转换为整数?

c# - 获取从 C# 中的 List<T> 派生的列表中的元素类型

haskell - 如何拥有一种具有可索引但可选元素(要求 Haskell 中存在)的类型

sql - SQL Server 2008 TIME 的精度可以降低到只有几小时和几分钟吗?

math - float 学坏了吗?