python - 使用 Ctypes 从 Python 中的 PARI/GP 获取数组/向量
问题描述
我已经编写了一个代码来比较 和 的解决方案,sympy
我PARI/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>
如何从中获取res
as 向量/数组,nfroots
以便可以像普通 python 向量/数组一样使用该数组?
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 整数的 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
推荐阅读
- r - 如何加载和查看大型 R 工作区
- excel - 从列表中打开静默 excel 文件以将值更改为特定单元格
- forms - 如何验证 Shopify 的“创建帐户”表单中的 2 个字段之间的文本输入不匹配?
- bash - 如何使用 bash 遍历文本文件第一列的元素?
- c# - 使用 QueueBackgroundWorkItem 运行后台线程时的 Castle Windsor 问题
- ios - 如何从 uitableviewcell 类中调用 segue?不是控制器
- javascript - 如何使 Lightpick 日历的日期格式响应窗口大小
- python - 寻找一种加速熊猫数据框搜索的方法
- dart - 使用 SizeTransition 小部件
- c# - 下载 Selenium,只获取 nupkg 文件,没有 dll