简体   繁体   English

使用Python求解五阶多项式

[英]Using Python to solve a 5th order polynomial

I think it is pretty clear from the title as to what I am trying to accomplish. 我认为从标题可以很清楚地知道我要完成什么。 So, let us get on with the code: 因此,让我们继续下面的代码:

import math

import numpy as np

import scipy

#from scipy import scipy.optimize.fsolve as sci_solve



x0 = -5

def function(x):

    x**5 + x**4 + x**3 + x**2 + x + 1

#print sci_solve(function, x0)

print scipy.optimize.fsolve(function, x0)

Okay, so when I run this code, I get [-5.]. 好的,所以当我运行这段代码时,我得到[-5。]。 When did it simply print my initial value, and not the roots of this equation? 它何时仅打印我的初始值,而不是该方程式的根? Also, when I ran the code without # before the lines containing the code #from scipy import scipy.optimize.fsolve as sci_solve and print sci_solve(function, x0), it gave me a syntax error. 另外,当我在包含#from scipy的代码的行之前运行不含#的代码时,将scipy.optimize.fsolve导入为sci_solve并打印sci_solve(function,x0),这给了我一个语法错误。

What am I doing wrong? 我究竟做错了什么?

As hcwhsa points out, I neglected to relate to the reader the version of python I am using, and I am terribly sorry for this. 正如hcwhsa指出的那样,我忽略了与读者联系我正在使用的python版本,对此我感到非常抱歉。 I am using version 2.7 我正在使用2.7版

在问这个问题之前,我从未真正听说过scipy模块(因此感谢您),但是从http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/给出的示例代码中old / node18.html ,看来您需要在def function(x):之后的多项式之前放一个return语句。

One way to do this: 一种方法是:

from scipy import *

x0 = -5
p = poly1d([1, 1, 1, 1, 1, 1])

# evaluate for x = x0
p(x0)

# get roots
roots(p)

This gives you all roots, including complex ones. 这为您提供了所有的根源,包括复杂的根源。 If you want only real roots, you can iterate over roots(p) (it's an array) and check that each item's imag attribute is 0.0. 如果只需要实根,则可以遍历roots(p)(它是一个数组),并检查每个项目的imag属性是否为0.0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM