gpt4 book ai didi

c# - .NET 的 Decimal 算术实现的确切规范是什么?

转载 作者:行者123 更新时间:2023-12-05 03:17:19 25 4
gpt4 key购买 nike

例如,

0.0000000000000000000000000001

表示为(lo mid hi flags):

1 0 0 1c0000

当上面除以10时,结果是(lo mid hi flags)

0 0 0 0

但是当它乘以0.1M时,结果是(lo mid hi flags)

0 0 0 1c0000

换句话说,根据十进制,0.0000000000000000000000000001 乘以 0.1 就是 0.000000000000000000000000000000。但除以 10 为 0。

下面是不同的结果:

var o = 0.0000000000000000000000000001M;
Console.WriteLine($"{o * 0.1M}");
Console.WriteLine($"{o / 10M}");

我需要能够在虚拟机中复制此行为和所有其他十进制算法。有人可以指出我的规范或解释理由吗? System.Decimal.cs 似乎没有提供见解。

更新:看来这只是十进制乘法实现中的一个错误。运算符应保留比例(根据 IEEE 754 2008),但乘法则不然。

最佳答案

language spec

The result of an operation on values of type decimal is that which would result from calculating an exact result (preserving scale, as defined for each operator) and then rounding to fit the representation. Results are rounded to the nearest representable value, and, when a result is equally close to two representable values, to the value that has an even number in the least significant digit position (this is known as “banker’s rounding”). That is, results are exact to at least the 28th decimal place. Note that rounding may produce a zero value from a non-zero value.

小数的精度为 28 位小数。您的示例中最接近的可表示值为零。

decimal d28 = 1e-28m; // 0.0000000000000000000000000001
d28 / 10

结果:0

类实现可用here .数学运算符在辅助类中实现 (DecCalc) here .

link to multiplication

link to division

来源(int[] bits 构造函数)的小注释,关于不同的表示(有效数字)在数值上是等价的

// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.

关于c# - .NET 的 Decimal 算术实现的确切规范是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74155377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com