在 SymPy 中使用其他基础系统

Using other base systems in SymPy

如何在 SymPy 中使用另一个基础系统?我想做类似于 Rational(string) 但不是以 10 为基数的事情。

您需要的大部分内容都可以在 Python 中找到:

def sdigits(s, b, tuple=False):
    p = len(s.split('.')[1])
    n, d = (int(s.replace('.', ''), base=b), b**p)
    if tuple:
        return n, d
    return '%s/%s' % (n, d)

这为以下内容生成,

sdigits('1.1', 3) -> '4/3'
sdigits('1.01', 3) -> '10/9'
sdigits('-1.12', 3) -> '-14/9'
sdigits('-1.12', 3, tuple=True) -> (-14, 9)
sdigits('1.2', 4) -> '6/4'

要受益于 SymPy 提供简化比率的能力,您可以将任一输出传递给 Rational:

Rational(sdigits('1.2', 4)) -> 3/2
Rational(*sdigits('1.2', 4, tuple=True)) -> 3/2