使用Ctypes在Python中从PARI / GP获取数组/向量 [英] Getting an Array/Vector from PARI/GP in Python using Ctypes

查看:188
本文介绍了使用Ctypes在Python中从PARI / GP获取数组/向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段代码来比较 sympy PARI / GP 的解决方案,从PARI / GP获取数组/向量的问题。

I have written a code to compare the solution of sympy and PARI/GP, how ever I am facing a problem to get an array/vector from PARI/GP.

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

When I try to return the vector res from PARI/GP function nfroots, I get a address like this (see the last line) -

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

如何获取 res 作为向量/ array from nfroots ,所以我可以像普通的python vector / array一样使用该数组?

how can I get the res as vector/array from nfroots so I can use that array like normal python vector/array?

代码如下要下载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)


推荐答案

res 是PARI / C世界中的一个元素。它是PARI整数(t_INT的t_VEC)的PARI向量。 Python不知道。

res is an element from the PARI/C world. It is a PARI vector of PARI integers (t_VEC of t_INTs). Python does not know it.

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

If it is to be processed further on the Python side, it must be converted. This is generally necessary if data needs to be exchanged between Python and the PARI/C world.

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

So if you have a t_VEC with t_INTs on the PARI/C side, as in this case, you most likely want to convert it to a Python list.

一种可能的方法如下:

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

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

这篇关于使用Ctypes在Python中从PARI / GP获取数组/向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆