2

我可能完全错了,我对此一无所知,但我对编程语言中的十进制数数据类型有疑问。我知道浮点数并不完全精确,因为它们以带有幂或其他东西的二进制存储,但我一直想知道为什么十进制数字数据类型不只是存储一个数字,就好像没有小数一样,所以计算为如果没有小数,则在后面加上。就像在这种情况下:

2.159 * 3.507 --> 2159 * 3507 = 7571613
  ^^^     ^^^
  123     456

6 decimals in total... 7571613 -> 7.571613
                        ^^^^^^
                        654321

所以 2.159 * 3.507 = 7.571613

为什么它不能那样工作?

4

3 回答 3

9

这正是他们所做的。浮点数以指数形式存储。假设我们正在使用基于十进制的计算机,因此我不必将所有这些数字都更改为二进制。

您正在乘以2.159 * 3.507,但实际上2.159存储为2159 * 10^-33.507存储为3507 * 10^-3。由于我们正在研究基于十进制的系统,10因此我们只需要在-3没有 的情况下进行存储10,例如:2159,-33507,-3. 这-3是“浮点”的位置:当点向左移动时,浮点数减少(.3507存储为3507,-4),当点向右移动时,浮点数增加(35.07存储为3507,-2)。

当你将两者相乘时,十进制数(或二进制计算机上的二进制数)是唯一被相乘的东西。 浮点数被添加! 所以在幕后发生的事情是:

2.159 * 3.507
2159,-3 * 3507,-3
2159 * 3507,-3 + -3
7571613,-6

7571613,-6 is just 7571613 * 10^-6 (remember we can assume the 10 because we're working on a decimal computer) which is the same as 7.571613.

Of course, the floating point doesn't have to be -3, it could be anything that fits into the storage:

21590 * .3507
2159,1 * 3507,-4
2159 * 3507,1 + -4
7571613,-3
7571.613

And of course, most computers don't store things in decimal, so the actual numbers would be all in binary, and the floating point would be something like 2^-9 -> -9 rather than 10^-3 -> -3. But you get the idea.

于 2009-08-17T03:14:34.083 回答
3

这就是所谓的“定点算术”,人们一直都在这样做。

http://gameprogrammer.com/4-fixed.html

于 2009-08-17T02:14:33.940 回答
1

定点算法有很多实现。然而,我们经常用定点存储非常非常快地用完小数位。它是货币交易的理想选择,我们知道我们不会存储/关心任何无理数。

此外,对于许多其他事情,定点算术不值得开销。浮点数要快得多。

阅读内容:

于 2009-08-17T02:24:19.627 回答