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程序设计有所帮助。

相关文章

numpy中的delete删除数组整行和整列的实例

numpy中的delete删除数组整行和整列的实例

numpy的delete是可以删除数组的整行和整列的,下面简单介绍和举例说明delete函数用法: numpy.delete(arr, obj, axis=None) 参数: ar...

python2.7的flask框架之引用js&css等静态文件的实现方法

python2.7的flask框架之引用js&css等静态文件的实现方法

动态 web 应用也会需要静态文件,通常是 CSS 和 JavaScript 文件。理想状况下, 我们已经配置好 Web 服务器来提供静态文件,但是在开发中,Flask 也可以做到。 只...

利用Python正则表达式过滤敏感词的方法

利用Python正则表达式过滤敏感词的方法

问题描述:很多网站会对用户发帖内容进行一定的检查,并自动把敏感词修改为特定的字符。 技术要点: 1)Python正则表达式模块re的sub()函数; 2)在正则表达式语法中,竖线“|”表...

selenium+python自动化测试环境搭建步骤

selenium+python自动化测试环境搭建步骤

相对于自动化测试工具QTP来说,selenium小巧、免费,而且兼容Google、FireFox、IE多种浏览器,越来越多的人开始使用selenium进行自动化测试。 我是使用的pyth...

python虚拟环境virualenv的安装与使用

前言 在安装完python及pip,setuptools等工具后,即可以创建virualenv虚拟环境了,这个类似于虚拟机的工具,可以让同一台电脑中运行多个不同版本的python程序,互...