【问题标题】:J's x-type variables: how are they stored internally?J 的 x 型变量:它们是如何在内部存储的?
【发布时间】:2014-06-11 09:44:33
【问题描述】:

我正在用 Python (https://gist.github.com/Synthetica9/73def2ec09d6ac491c98) 编写一些 J 绑定。但是,我在处理任意精度整数时遇到了一个问题:输出没有任何意义。每次都是不同的(但总体上是相同的)。相关代码:

def JTypes(desc, master):
    newdesc = [item.contents.value for item in desc]
    type = newdesc[0]
    if debug: print type
    rank = newdesc[1]
    shape = ct.c_int.from_address(newdesc[2]).value
    adress = newdesc[3]
    #string
    if type == 2:
        charlist = (ct.c_char.from_address(adress+i) for i in range(shape))
        return "".join((i.value for i in charlist))
    #integer
    if type == 4:
        return ct.c_int.from_address(adress).value
    #arb-price int
    if type == 64:
        return ct.c_int.from_address(adress).value

class J(object):
    def __init__(self):
        self.JDll = ct.cdll.LoadLibrary(os.path.join(jDir, "j.dll"))
        self.JProc = self.JDll.JInit()

    def __call__(self, code):
        #Exec code, I suppose.
        self.JDll.JDo(self.JProc, "tmp=:"+code)
        return JTypes(self.deepvar("tmp"),self)

我们将不胜感激。

【问题讨论】:

    标签: python data-structures j


    【解决方案1】:

    简答:J 的扩展精度整数存储在base 10,000

    更具体地说:单个扩展整数存储为机器整数数组,每个整数都在 [0,1e4) 范围内。因此,扩展整数数组存储为recursive data structure。扩展整数数组的 type=64(“扩展整数”),它的元素,每个本身(指向)数组的元素,都有 type=4(“整数”)。

    因此,从概念上讲(使用 J 表示法),大整数数组:

    123456 7890123 456789012x
    

    存储为机器整数的嵌套数组,每个小于 10,000:

       1e4 #.^:_1&.> 123456 7890123 456789012x
    +-------+-------+-----------+
    |12 3456|789 123|4 5678 9012|
    +-------+-------+-----------+
    

    因此,要恢复原始大数,您必须以 10,000 为底来解释这些数字¹:

       10000x #.&> 12 3456 ; 789 123 ; 4 5678 9012   
    123456 7890123 456789012
    

    J 中唯一的其他“x 类型变量”是有理数,不出所料,它们存储为一对扩展精度整数(一个用于分子,另一个用于分母)。因此,如果您有一个数组,其标头指示 type='rational' 且 count=3,则其数据段将有 6 个元素(2*3)。把这些成对地拿,你就有了你的比率数组。

    如果您尝试构建一个完整的 J-Python 接口,您还必须处理类似嵌套的盒装和稀疏数组。通过使用tools built in to J 检查 J 名词的二进制和十六进制表示,您可以学到很多东西。

    哦,如果您想知道为什么 J 以 10,000 为底数存储 bignums?这是因为 10,000 足以保持嵌套数组紧凑,并且是 10 的幂表示 makes it easy to format numbers in decimal


    ¹ 注意调整字节顺序(例如,4 5678 9012 在内存中可能表示为 9012 5678 4)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2017-05-15
      相关资源
      最近更新 更多