将分数从十进制转换为二进制 [英] Convert fractions from decimal to binary
问题描述
我想将数字8.7转换为二进制.
I want to convert the number 8.7 to binary.
我知道命令
(format nil "~b" (rationalize 8.7)) ===>
1010111/1010
或
(format nil "~b" (/ 87 10))====> 1010111/1010
我们观察是否对商1010111/1010做商得到1000.1011001100110011001100110011.
We observe if we do the quotient binary 1010111/1010 we obtain 1000.1011001100110011001100110011.
有可能在Lisp中获得
Is possible to obtain in Lisp
(8.7)_2 ~ 1000.1011001100110011001100110011?
如果是,怎么办?
推荐答案
"2.718 ..."等于2 * 10^1 + 7 * 10^-1 + 1 * 10^-2 + 8 * 10^-3
...这意味着您可以通过连接string(n / base^i)
的反向过程来生成字符串,其中 i 是字符串的索引,而 n 是仍需要转换为 base 的值.本质上,这是一种贪婪的变更决策算法.
"2.718..." is equal to 2 * 10^1 + 7 * 10^-1 + 1 * 10^-2 + 8 * 10^-3
... This means that you can generate the string by the reverse process of concatenating string(n / base^i)
where i is the index into the string and n is the value that still needs to be converted to base. It's essentially a greedy change-making algorithm.
以下内容大致可行,但不能保证它会产生确切的IEEE 754分数.它应该与实现的浮动一样准确
The following roughly works, with no guarantee that it produces the exact IEEE 754 fraction. It should be as accurate as your implementation's floats
(defun fractional-binary (fractional &optional (place 1) (result "."))
(if (zerop fractional)
result
(let ((fraction (expt 2 (- place))))
(if (<= fraction fractional)
(fractional-binary (- fractional fraction)
(1+ place)
(concatenate 'string result "1"))
(fractional-binary fractional
(1+ place)
(concatenate 'string result "0"))))))
CL-USER> (fractional-binary .7)
".101100110011001100110011"
这篇关于将分数从十进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!