我可以说出使用double(或float)而不是decimal的三个优点:
使用较少的内存。
更快是因为浮点数学运算是由处理器原生支持的。
可以表示更大范围的数字。
但这些优势似乎只适用于计算密集型操作,比如在建模软件中发现的那些操作。当然,当需要精度时,不应该使用双精度,例如财务计算。那么,在“正常”应用程序中选择双位数(或浮点数)而不是十进制有什么实际的原因吗?
编辑补充:
谢谢你们的回复,我从他们身上学到了很多。
还有一个问题:一些人认为双数可以更精确地表示实数。当我宣布时,我认为他们通常更准确地代表他们。但是,当执行浮点运算时,精度可能会降低(有时会显著降低),这是真的吗?
Decimal具有更宽的字节,CPU原生支持double。十进制是以10为基数的,所以在计算十进制时发生了十进制到双精度的转换。
For accounting - decimal
For finance - double
For heavy computation - double
请记住。net CLR只支持Math.Pow(double,double)。不支持十进制。
.NET Framework 4
[SecuritySafeCritical]
public static extern double Pow(double x, double y);
注意:这篇文章是基于来自http://csharpindepth.com/Articles/General/Decimal.aspx的十进制类型的功能信息和我自己的解释。我假设Double是标准的IEEE双精度。
注2:本文中的最小和最大是指数字的大小。
“decimal”的优点。
“decimal”可以精确地表示可以写成(足够短的)十进制分数的数字,而double则不能。这在财务账本中很重要,在类似的地方,重要的是计算结果与人类进行计算的结果完全匹配。
“decimal”的尾数比“double”大得多。这意味着在它的标准化范围内的值,“十进制”将具有比双精度更高的精度。
十进制的缺点
It will be Much slower (I don't have benchmarks but I would guess at least an order of magnitude maybe more), decimal will not benefit from any hardware acceleration and arithmetic on it will require relatively expensive multiplication/division by powers of 10 (which is far more expensive than multiplication and dividion by powers of 2) to match the exponent before addition/subtraction and to bring the exponent back into range after multiplication/division.
decimal will overflow earlier tha double will. decimal can only represent numbers up to ±296-1 . By comparision double can represent numbers up to nearly ±21024
decimal will underflow earlier. The smallest numbers representable in decimal are ±10-28 . By comparision double can represent values down to 2-149 (approx 10-45) if subnromal numbers are supported and 2-126 (approx 10-38) if they are not.
decimal takes up twice as much memory as double.
我的观点是,对于金钱工作和其他与人工计算完全匹配很重要的情况,您应该默认使用“decimal”,并且在其他情况下,您应该使用use double作为默认选择。
I think you've summarised the advantages quite well. You are however missing one point. The decimal type is only more accurate at representing base 10 numbers (e.g. those used in currency/financial calculations). In general, the double type is going to offer at least as great precision (someone correct me if I'm wrong) and definitely greater speed for arbitrary real numbers. The simple conclusion is: when considering which to use, always use double unless you need the base 10 accuracy that decimal offers.
编辑:
关于您关于操作后浮点数精度下降的附加问题,这是一个稍微微妙的问题。实际上,每次操作执行后,精度(我在这里交替使用准确性这个术语)都会稳步下降。这有两个原因:
某些数字(最明显的是小数)不能真正地用浮点形式表示
会出现舍入错误,就像手工计算一样。然而,这些错误是否严重到值得仔细考虑,很大程度上取决于上下文(您正在执行多少个操作)。
在所有情况下,如果您想比较理论上应该等效的两个浮点数(但使用不同的计算方法得到),则需要允许一定程度的容错(容错程度不同,但通常非常小)。
有关可能引入准确性错误的特定情况的更详细概述,请参阅维基百科文章的准确性部分。最后,如果你想深入地(和数学地)讨论机器级别的浮点数/操作,试着阅读经常被引用的文章《每个计算机科学家都应该知道浮点算术》。