我已经阅读了一些文本和线程,展示了如何从小数转换为 IEEE 754,但我仍然对如何在不扩展小数的情况下转换数字(以科学记数法表示)感到困惑
我特别使用的数字是9.07 * 10^23
,但任何数字都可以;对于我的特定示例,我将弄清楚如何做到这一点。
我已经阅读了一些文本和线程,展示了如何从小数转换为 IEEE 754,但我仍然对如何在不扩展小数的情况下转换数字(以科学记数法表示)感到困惑
我特别使用的数字是9.07 * 10^23
,但任何数字都可以;对于我的特定示例,我将弄清楚如何做到这一点。
我假设您希望结果是最接近十进制数的浮点数,并且您使用的是双精度浮点数。
对于大多数数字,有一种方法可以相对快速地完成。简而言之,这是它的工作原理。
您需要将数字拆分为具有精确表示为浮点数的乘积或数字的一部分。可精确表示的 10 的最大幂是 10^22。因此,要获得浮点形式的 9.07e+23,我们可以这样写:
9.07e+23 = 907 * 10^21
根据 IEEE-754 标准,保证单个浮点运算被正确舍入,因此上述乘积计算为 2 个双精度浮点数的乘积,将给出正确舍入的结果。
如果您要在转换函数中使用它,您可能会将 10 的幂存储在一个数组中。
请注意,您不能将此方法用于 9.07e-23。这个数字等于 907 / 10^23,因此分母太大而无法精确表示。在这种情况下,以及其他处理非常大或非常小的数字时,您必须使用某种形式的高精度算术。
有关更多详细信息和示例,请参阅快速路径十进制到浮点转换。
Converting a number from a decimal string to binary IEEE is fairly straight-forward if you know how to do IEEE floating-point addition and multiplication. (or if you're using any basic programming language like C/C++)
There's a lot of different approaches to this, but the easiest is to evaluate 9.07 * 10^23
directly.
First, start with 9.07
:
9.07 = 9 + 0 * 10^-1 + 7 * 10^-2
Now evaluate 10^23
. This can be done by starting with 10 and using any powering algorithm.
Then multiply the results together.
Here's a simple implementation in C/C++:
double mantissa = 9;
mantissa += 0 / 10.;
mantissa += 7 / 100.;
double exp = 1;
for (int i = 0; i < 23; i++){
exp *= 10;
}
double result = mantissa * exp;
Now, going backwards (IEEE -> to decimal) is a lot harder.
Again, there's also a lot of different approaches. Here's the easiest one I can think of it.
I'll use 1.0011101b * 2^40
as the example. (the mantissa is in binary)
First, convert the mantissa to decimal: (this should be easy, since there's no exponent)
1.0011101b * 2^40 = 1.22656 * 2^40
Now, "scale" the number such that the binary exponent vanishes. This is done by multiplying by an appropriate power of 10 to "get rid" of the binary exponent.
1.22656 * 2^40 = 1.22656 * (2^40 * 10^-12) * 10^12
= 1.22656 * (1.09951) * 10^12
= 1.34861 * 10^12
So the answer is:
1.0011101b * 2^40 = 1.34861 * 10^12
In this example, 10^12
was needed to "scale away" the 2^40
. Determining the power of 10 that is needed is simply equal to:
power of 10 = (power of 2) * log(2)/log(10)