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

相关文章

pymongo实现控制mongodb中数字字段做加法的方法

本文实例讲述了pymongo实现控制mongodb中数字字段做加法的方法。分享给大家供大家参考。具体分析如下: 这个非常实用,比如我们需要给文章做访问统计,可以设置一个数字字段:hit,...

Python二维码生成识别实例详解

前言 在 JavaWeb 开发中,一般使用 Zxing 来生成和识别二维码,但是,Zxing 的识别有点差强人意,不少相对模糊的二维码识别率很低。不过就最新版本的测试来说,识别率有了现...

Python range、enumerate和zip函数用法详解

前言 range函数可创建一个整数列表。 如果需要知道当前元素在列表中的索引,推荐用enumerate代替range。 zip函数用于同时遍历多个迭代器。 一、range 函数 ra...

Python求平面内点到直线距离的实现

Python求平面内点到直线距离的实现

近期遇到个问题,需要计算平面内点到直线的距离,发现数学知识都还给老师了,度娘后找到计算方法,特此记录。 点到直线的计算公式: 通过公式推导,得到信息: A:直线斜率 B:固定值-1 C...

解决Pandas的DataFrame输出截断和省略的问题

解决Pandas的DataFrame输出截断和省略的问题

我们看一个现象: import pandas as pd titanic = pd.read_csv('titanic_data.csv') print(titanic.head()...