[英]Python package for multiplying polynomials with large coefficients
I want to multiply multiply polynomials with large coefficients in python. 我想在python中用大系数乘以多项式。 I tried this in numpy. 我在numpy中尝试过。
import numpy as np
p = np.poly1d([1])
for i in range(250):
p = np.polymul(p, [1, 2])
print ("P : ", p)
But suprisingly, numpy is giving wrong results! 但是令人惊讶的是,numpy给出了错误的结果! Ideally the program should expand the polynomial (x+2)^250 and output it. 理想情况下,程序应扩展多项式(x + 2)^ 250并输出。 But it outputs the following. 但是它输出以下内容。
P : 250 249 248 247 246
1 x + 500 x + 1.245e+05 x + 2.058e+07 x + 2.542e+09 x
245 244 243 242
+ 2.501e+11 x + 2.043e+13 x + 1.424e+15 x + 8.652e+16 x
241 240 239 238
+ 4.653e+18 x + 2.901e+18 x + 9.18e+18 x + 9.015e+18 x
237 236 235 234
- 7.634e+18 x - 1.988e+17 x - 8.716e+18 x + 6.834e+18 x
233 232 231 230
- 3.933e+18 x + 2.712e+18 x + 6.03e+18 x - 4.58e+18 x
229 228 227 226
+ 7.714e+18 x - 5.435e+18 x + 3.734e+18 x + 4.537e+18 x
225 224 223 222
- 6.507e+18 x - 1.937e+18 x + 6.602e+17 x + 2.61e+18 x
221 220 219 218
- 3.935e+18 x + 8.436e+18 x + 6.076e+18 x - 5.604e+18 x
217 216 215 214
+ 2.542e+18 x + 3.146e+18 x + 3.515e+18 x - 3.458e+16 x
213 212 211 210
- 5.884e+18 x + 5.881e+18 x - 3.702e+18 x + 6.049e+17 x
209 208 207 206
- 9.101e+18 x - 5.37e+18 x - 8.623e+18 x + 5.234e+18 x
205 204 203 202
+ 4.466e+18 x + 8.528e+18 x - 5.645e+18 x + 6.822e+18 x
201 200 199 198
+ 2.037e+18 x - 2.809e+18 x + 5.819e+18 x + 2.675e+18 x
197 196 195 194
+ 7.458e+18 x + 5.224e+18 x + 2.018e+18 x - 9.007e+18 x
193 192
- 1.441e+18 x - 2.594e+18 x
There seems to be some precision issues with the function. 该函数似乎存在一些精度问题。 Is there any library in python that is suitable for multiplying polynomials with large coefficients? python中是否有适合于将系数大的多项式相乘的库?
Sympy would be a good bet. Sympy将是一个不错的选择。 Doing this in sympy would look something like: 在sympy中执行此操作看起来像:
import sympy
x = sympy.var('x')
p = (x+2)**250
p = sympy.expand(p)
print(p)
I have not included the output as it is quite long, but spot checking it looks correct. 我没有包括输出,因为它很长,但是抽查它看起来是正确的。 Sympy uses arbitrary precision libraries, so all coefficients are expanded out. Sympy使用任意精度库,因此可以扩展所有系数。 You can get individual coefficients by using the coeff
method. 您可以使用coeff
方法获得各个系数。 Eg: 例如:
>> p.coeff(x**249)
250
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.