到目前为止,我总是使用Mathematica来求解解析方程式。然而,现在我需要解决这种类型的几百个方程(特征多项式)
a_20*x^20+a_19*x^19+...+a_1*x+a_0=0 (constant floats a_0,...a_20)
立即在Mathematica中产生非常长的计算时间。
是否有像numpy或任何其他包中的现成命令来解决这种类型的等式? (到目前为止,我只使用Python进行模拟,因此我对分析工具知之甚少,而且在numpy教程中找不到任何有用的东西)。
答案 0 :(得分:6)
你使用numpy(显然),但我自己从未尝试过:http://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html#numpy.roots。
Numpy还提供了一个多项式类...... numpy.poly1d。
这在数字上找到根源 - 如果你想要分析根源,我认为numpy不能为你做到这一点。
答案 1 :(得分:4)
答案 2 :(得分:4)
以下是来自simpy docs的示例:
>>> 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
答案 3 :(得分:-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)