C#中不是15位的Double Type精度吗? [英] Wasn't the Double Type precision of 15 digits in C#?

查看:177
本文介绍了C#中不是15位的Double Type精度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从脑筋急转弯:

        double d1 = 1.000001;

        double d2 = 0.000001;

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

结果为"False".当我更改数据类型时:

And the result is "False". When I change the data type:

        decimal d1 = 1.000001M;

        decimal d2 = 0.000001M;

        decimal d3 = d1-d2;

        Console.WriteLine(d3 == 1);

程序将写入正确的答案:"True".

The program writes the correct answer: "True".

此问题仅在浮点后使用6位数字. 15位精度会发生什么情况?

This problem just uses 6 digits after the floating point. What happened with the precision of 15 digits?

推荐答案

这与精度无关-它与表示取整错误有关.

This has nothing to do with precision - it has to do with representational rounding errors.

System.Decimal能够表示较大的浮点数,从而显着降低发生舍入错误(如您所看到的舍入错误)的风险. System.SingleSystem.Double无法做到这一点,它们会将这些数字四舍五入,并产生类似示例中出现的问题.

System.Decimal is capable of representing large floating point numbers with a significantly reduced risk of incurring any rounding errors like the one you are seeing. System.Single and System.Double are not capable of this and will round these numbers off and create issues like the one you are seeing in your example.

System.Decimal使用比例因子保持小数位的位置,从而可以精确表示给定的浮点数,而System.SingleSystem.Double仅尽可能地近似您的值.

System.Decimal uses a scaling factor to hold the position of the decimal place thus allowing for exact representation of the given floating-point number, whereas System.Single and System.Double only approximate your value as best they can.

有关更多信息,请参见 System.Double :

For more information, please see System.Double:

请记住,浮点数 只能近似十进制数 而且那个的精度 浮点数决定了 准确地讲,这个数字近似为 十进制数.默认情况下,Double 值包含15个十进制数字 精度,尽管最大为17 数字在内部维护.这 浮点数的精度 有几个后果:

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#中不是15位的Double Type精度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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