我正在测试来自 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.Single
和 System.Double
无法做到这一点,它们会将这些数字四舍五入并产生类似于您在示例中看到的问题。
System.Decimal
使用比例因子来保持小数位的位置,从而允许精确表示给定的 float ,而 System.Single
和System.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/