汇总表示Sagemath中分数的二进制数

时间:2017-05-18 06:13:57

标签: binary addition sage fractions

我刚开始学习如何在Sagemath中编码,我知道它与python类似,但我对此也没有多少经验。
我正在尝试添加两个代表分数的二进制数。就是这样的事情

a = '110'  
b = '011'  
bin(int(a,2) + int(b,2))  

但是使用代表分数的值,例如'1.1' 提前谢谢!

2 个答案:

答案 0 :(得分:0)

如果你想在vanilla Python中这样做,手工解析二进制分数也不错(第一部分来自this answer);

cat /proc/net/stat/arp_cache | sed -e '2,$s/\s*\([0-9a-f][0-9a-f]*\)\s*/ \$\(\( 0x\1 \)\) /g' -e 's/^/echo /' | bash | column -t
entries  allocs  destroys  hash_grows  lookups  hits  res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
8        2       0         0           0        0     0           0                 0                 0                 0               0                    0
8        0       0         0           211      58    0           0                 0                 0                 0               0                    0
8        2       0         0           6319     1677  0           0                 0                 3882              0               0                    0
8        4       0         0           4731     1299  0           0                 0                 0                 0               0                    0

答案 1 :(得分:0)

在 python 中,您可以使用 Binary fractions 包。使用此包,您可以将二进制分数字符串转换为浮点数,反之亦然。然后,您可以对其进行操作。

示例:

>>> from binary_fractions import Binary
>>> sum = Binary("1.1") + Binary("10.01")
>>> str(sum)
'0b11.11'
>>> float(sum)
3.75
>>>

它有更多的辅助函数来操作二进制字符串,例如:shift、add、fill、to_exponential、invert...

PS:无耻的插件,我是这个包的作者。

相关问题