python计算方程式根的方法

yipeiwu_com5年前Python基础

本文实例讲述了python计算方程式根的方法。分享给大家供大家参考。具体实现方法如下:

''' roots = polyRoots(a).
  Uses Laguerre's method to compute all the roots of
  a[0] + a[1]*x + a[2]*x^2 +...+ a[n]*x^n = 0.
  The roots are returned in the array 'roots',
'''  
from evalPoly import *
from numpy import zeros,complex
from cmath import sqrt
from random import random
def polyRoots(a,tol=1.0e-12):
  def laguerre(a,tol):
    x = random()
    # Starting value (random number)
    n = len(a) - 1
    for i in range(30):
      p,dp,ddp = evalPoly(a,x)
      if abs(p) < tol: return x
      g = dp/p
      h = g*g - ddp/p
      f = sqrt((n - 1)*(n*h - g*g))
      if abs(g + f) > abs(g - f): dx = n/(g + f)
      else: dx = n/(g - f)
      x = x - dx
      if abs(dx) < tol: return x
    print 'Too many iterations'
  def deflPoly(a,root): # Deflates a polynomial
    n = len(a)-1
    b = [(0.0 + 0.0j)]*n
    b[n-1] = a[n]
    for i in range(n-2,-1,-1):
      b[i] = a[i+1] + root*b[i+1]
    return b
  n = len(a) - 1
  roots = zeros((n),dtype=complex)
  for i in range(n):
    x = laguerre(a,tol)
    if abs(x.imag) < tol: x = x.real
    roots[i] = x
    a = deflPoly(a,x)
  return roots
  raw_input("\nPress return to exit")

希望本文所述对大家的Python程序设计有所帮助。

相关文章

基于windows下pip安装python模块时报错总结

基于windows下pip安装python模块时报错总结

这几天把python版本升级后,发现pip安装模块好多都报错(暂不确定是不是因为升级导致的),我定睛一看,发现是权限的问题,那么怎么解决呢? 1 权限问题 C:\Users\ljf&...

Python根据已知邻接矩阵绘制无向图操作示例

Python根据已知邻接矩阵绘制无向图操作示例

本文实例讲述了Python根据已知邻接矩阵绘制无向图操作。分享给大家供大家参考,具体如下: 有六个点:[0,1,2,3,4,5,6],六个点之间的邻接矩阵如表格所示,根据邻接矩阵绘制出相...

Python3处理文件中每个词的方法

本文实例讲述了Python3处理文件中每个词的方法。分享给大家供大家参考。具体实现方法如下: ''''' Created on Dec 21, 2012 处理文件中的每个词 @...

利用Python读取文件的四种不同方法比对

前言 大家都知道Python 读文件的方式多种多样,但是当需要读取一个大文件的时候,不同的读取方式会有不一样的效果。下面就来看看详细的介绍吧。 场景 逐行读取一个 2.9G 的大文件...

python数组循环处理方法

简介 本文主要介绍python数组循环语法。主要方式有元素遍历,索引遍历,enumerate, zip, list内部等。 普通循环 list1 = ['item1', 'item2...