首页 > 解决方案 > 使用 Ctypes 从 Python 中的 PARI/GP 获取数组/向量

问题描述

我已经编写了一个代码来比较 和 的解决方案,sympyPARI/GP如何从 PARI/GP 获取数组/向量时遇到问题。

当我尝试res从 PARI/GP 函数返回向量时nfroots,我得到一个这样的地址(见最后一行) -

    [3, 4]
elements as long (only if of type t_INT): 
3
4
<__main__.LP_LP_c_long object at 0x00000000056166C8>

如何从中获取resas 向量/数组,nfroots以便可以像普通 python 向量/数组一样使用该数组?

下面给出了下载libpari.dll文件的代码,点击这里-

from ctypes import *
from sympy.solvers import solve
from sympy import Symbol

pari = cdll.LoadLibrary("libpari.dll")
pari.stoi.restype = POINTER(c_long)
pari.cgetg.restype = POINTER(POINTER(c_long))
pari.gtopoly.restype = POINTER(c_long)
pari.nfroots.restype = POINTER(POINTER(c_long))

(t_VEC, t_COL, t_MAT) = (17, 18, 19)  # incomplete
pari.pari_init(2 ** 19, 0)


def t_vec(numbers):
    l = len(numbers) + 1
    p1 = pari.cgetg(c_long(l), c_long(t_VEC))
    for i in range(1, l):
        #Changed c_long to c_float, but got no output
        p1[i] = pari.stoi(c_long(numbers[i - 1]))
    return p1


def Quartic_Comparison():
    x = Symbol('x')
    #a=0;A=0;B=1;C=-7;D=13/12 #PROBLEM 1
    a=0;A=0;B=1;C=-7;D=12
    #a=0;A=0;B=-1;C=-2;D=1
    solution=solve(a*x**4+A*x**3+B*x**2+ C*x + D, x)
    print(solution)
    V=(A,B,C,D)
    P = pari.gtopoly(t_vec(V), c_long(-1))
    res = pari.nfroots(None, P)

    print("elements as long (only if of type t_INT): ")
    for i in range(1, pari.glength(res) + 1):        
         print(pari.itos(res[i]))
    return res               #PROBLEM 2

f=Quartic_Comparison()
print(f)

标签: pythonarraysvectorctypepari

解决方案


res是来自 PARI/C 世界的元素。它是 PARI 整数的 PARI 向量(t_INTs 的 t_VEC)。Python 不知道。

如果要在 Python 端进一步处理,则必须对其进行转换。如果需要在 Python 和 PARI/C 世界之间交换数据,这通常是必要的。

因此,如果您在 PARI/C 端有一个带有 t_INTs 的 t_VEC,就像在这种情况下,您很可能希望将其转换为 Python 列表。

一种可能的方法可能如下所示:

...
roots = pari.nfroots(None, P)

result = []
for i in range(1, pari.glength(roots) + 1):
    result.append(pari.itos(roots[i]))
return result

推荐阅读