[Python] python计算方程式的根的代码 →→→→→进入此内容的聊天室

来自 , 2019-02-17, 写在 Python, 查看 86 次.
URL http://www.code666.cn/view/da40657c
  1. ''' roots = polyRoots(a).
  2.    Uses Laguerre's method to compute all the roots of
  3.    a[0] + a[1]*x + a[2]*x^2 +...+ a[n]*x^n = 0.
  4.    The roots are returned in the array 'roots',
  5. '''    
  6. from evalPoly import *
  7. from numpy import zeros,complex
  8. from cmath import sqrt
  9. from random import random
  10.  
  11. def polyRoots(a,tol=1.0e-12):
  12.  
  13.     def laguerre(a,tol):
  14.         x = random()   # Starting value (random number)
  15.         n = len(a) - 1
  16.         for i in range(30):
  17.             p,dp,ddp = evalPoly(a,x)
  18.             if abs(p) < tol: return x
  19.             g = dp/p
  20.             h = g*g - ddp/p
  21.             f = sqrt((n - 1)*(n*h - g*g))
  22.             if abs(g + f) > abs(g - f): dx = n/(g + f)
  23.             else: dx = n/(g - f)
  24.             x = x - dx
  25.             if abs(dx) < tol: return x
  26.         print 'Too many iterations'
  27.  
  28.     def deflPoly(a,root):  # Deflates a polynomial
  29.         n = len(a)-1
  30.         b = [(0.0 + 0.0j)]*n
  31.         b[n-1] = a[n]
  32.         for i in range(n-2,-1,-1):
  33.             b[i] = a[i+1] + root*b[i+1]
  34.         return b
  35.  
  36.     n = len(a) - 1
  37.     roots = zeros((n),dtype=complex)
  38.     for i in range(n):
  39.         x = laguerre(a,tol)
  40.         if abs(x.imag) < tol: x = x.real
  41.         roots[i] = x
  42.         a = deflPoly(a,x)
  43.     return roots
  44.     raw_input("\nPress return to exit")
  45. #//python/7405

回复 "python计算方程式的根的代码"

这儿你可以回复上面这条便签

captcha