IEEE 754 浮点表示

发布于 2024-12-18 04:36:52 字数 102 浏览 7 评论 0原文

如何从十进制转换为 IEEE 745 浮点单精度? 我可以使用 0.5、0.75 等小数字 我的问题是我不知道如何处理较小的数字。 例如,

12.1325 * 10^-13

How do I convert from decimal to IEEE 745 Floating point single precision ?
I can work with small numbers like 0.5, 0.75, etc
My problem is that I've no idea what to do with smaller numbers.
For example,

12.1325 * 10^-13

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁许谁一生繁华 2024-12-25 04:36:52

我假设困难在于二进制转换而不是 IEEE 浮点编码(因为你说你知道如何转换 0.5 和 0.75)。对于不太简单的示例,例如 12.1325 * 10-13,我会使用我的 二进制转换器)。到 70 位,0.00000000000121325 是

0.0000000000000000000000000000000000000001010101010111111111100000001111...

(手动)四舍五入到 24 个有效位,即
0.00000000000000000000000000000000000000010101010101111111111

从那里开始,可以很简单地将其编码为浮点数。

另一种方法是分析(不过,您需要一个好的任意精度计算器的帮助,例如 PARI/GP)。首先将 12.1325 * 10-13 重写为 121325/1017,并尝试找到最接近的具有 24 位分子和二次分母幂的数字:

121325/10 17 = x/2n

x = (2n * 121325)/1017

您会发现 n=63 给出了您想要的结果:x = 11190256.123714056749056 = 11190256(四舍五入到最接近的值时)整数)。 (11190256 = 101010101011111111110000 二进制,您会看到它与上面的答案匹配。)标准化浮点时,您将从指数中减去 23,得到: 1.0101010101111111111 * 2-40

(对于后一种方法见我的文章使用大整数将小数正确转换为浮点.)

I'll assume the difficulty is the binary conversion and not the IEEE float encoding (since you say you know how to convert 0.5 and 0.75). For less straightforward examples, like 12.1325 * 10-13, I would use my binary converter). To 70 places, 0.00000000000121325 is

0.0000000000000000000000000000000000000001010101010111111111100000001111...

Rounded (by hand) to 24 significant bits, that's
0.00000000000000000000000000000000000000010101010101111111111

From there, it's straitforward to encode this as a float.

Another way to do this is analytically (you'll need the help of a good arbitrary-precision calculator though, like PARI/GP). Start by rewriting 12.1325 * 10-13 as 121325/1017, and try to find the closest number with a 24-bit numerator and power of two denominator:

121325/1017 = x/2n

x = (2n * 121325)/1017

You'll discover that n=63 gives you what you're after: x = 11190256.123714056749056 = 11190256 (when rounded to the nearest integer). (11190256 = 101010101011111111110000 in binary, and you'll see that matches the answer above.) When you normalize the float, you'll subtract 23 from the exponent, giving: 1.0101010101111111111 * 2-40

(For the latter method, see my article Correct Decimal To Floating-Point Using Big Integers.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文