2012-05-04 695 views
7

到目前为止,我总是用Mathematica来求解解析方程。但是现在,我需要解决几百方程这种类型的(特征多项式)在Python中求解多项式方程

a_20*x^20+a_19*x^19+...+a_1*x+a_0=0 (constant floats a_0,...a_20) 

同时这将产生相当长的计算时间的数学。

有没有像numpy或任何其他包中的准备使用命令来解决这种类型的公式? (到目前为止,我只用Python进行模拟,所以我对分析工具了解不多,在numpy教程中找不到任何有用的东西)。

+2

考虑sympy。 – Marcin

+3

为什么你认为python比mathematica快? – Falmarri

回答

4

你可能想看看SAGE这是一个完整的python发行版,专为数学处理而设计。除此之外,Marcin强调,我曾用Sympy来处理类似的事情。

+1

是的,SAGE非常好(尽管它可能会使用Numpy来完成这些任务)。 –

4

这里是从的simpy文档的例子:

>>> from sympy import * 
>>> x = symbols('x') 
>>> from sympy import roots, solve_poly_system 

>>> solve(x**3 + 2*x + 3, x) 
      ____   ____ 
    1 \/ 11 *I 1 \/ 11 *I 
[-1, - - --------, - + --------] 
    2  2  2  2 

>>> p = Symbol('p') 
>>> q = Symbol('q') 

>>> sorted(solve(x**2 + p*x + q, x)) 
      __________   __________ 
     /2    /2 
    p \/ p - 4*q  p \/ p - 4*q 
[- - + -------------, - - - -------------] 
    2   2   2   2 

>>> solve_poly_system([y - x, x - 5], x, y) 
[(5, 5)] 

>>> solve_poly_system([y**2 - x**3 + 1, y*x], x, y) 
            ___     ___ 
          1 \/ 3 *I   1 \/ 3 *I 
[(0, I), (0, -I), (1, 0), (- - + -------, 0), (- - - -------, 0)] 
          2  2   2  2 

a link to the docs with this example

-1
import decimal as dd 
degree = int(input('What is the highest co-efficient of x? ')) 
coeffs = [0]* (degree + 1) 
coeffs1 = {} 
dd.getcontext().prec = 10 
for ii in range(degree,-1,-1): 
    if ii != 0: 
     res=dd.Decimal(input('what is the coefficient of x^ %s ? '%ii)) 
     coeffs[ii] = res 
     coeffs1.setdefault('x^ %s ' % ii, res) 
    else: 
     res=dd.Decimal(input('what is the constant term ? ')) 
     coeffs[ii] = res 
     coeffs1.setdefault('CT', res) 
coeffs = coeffs[::-1] 
def contextmg(start,stop,step): 
    r = start 
    while r < stop: 
     yield r 
     r += step 
def ell(a,b,c): 
    vals=contextmg(a,b,c) 
    context = ['%.10f' % it for it in vals] 
    return context 
labels = [0]*degree 
for ll in range(degree): 
    labels[ll] = 'x%s'%(ll+1) 
roots = {} 
context = ell(-20,20,0.0001) 
for x in context: 
    for xx in range(degree): 
     if xx == 0: 
      calculatoR = (coeffs[xx]* dd.Decimal(x)) + coeffs[xx+1] 
     else: 
      calculatoR = calculatoR * dd.Decimal(x) + coeffs[xx+1] 

    func =round(float(calculatoR),2) 
    xp = round(float(x),3) 
    if func==0 and roots=={} : 
     roots[labels[0]] = xp 
     labels = labels[1:] 
     p = xp 
    elif func == 0 and xp >(0.25 + p): 
     roots[labels[0]] = xp 
     labels = labels[1:] 
     p = xp 

print(roots) 
+0

这几行代码只是在python 3中使用简单的逻辑,并且只输入1个模块。这个代码可以用来解决任何长度的多项式 – Uraniumkid30