[Python] Find the coefficients of the polynomial that fits →→→→→进入此内容的聊天室

来自 , 2019-12-05, 写在 Python, 查看 109 次.
URL http://www.code666.cn/view/2d1ef8f3
  1. ''' c = polyFit(xData,yData,m).
  2.    Returns coefficients of the polynomial
  3.    p(x) = c[0] + c[1]x + c[2]x^2 +...+ c[m]x^m
  4.    that fits the specified data in the least
  5.    squares sense.
  6.  
  7.    sigma = stdDev(c,xData,yData).
  8.    Computes the std. deviation between p(x)
  9.    and the data.
  10. '''    
  11. from numpy import zeros
  12. from math import sqrt
  13. from gaussPivot import *
  14.  
  15. def polyFit(xData,yData,m):
  16.     a = zeros((m+1,m+1))
  17.     b = zeros(m+1)
  18.     s = zeros(2*m+1)
  19.     for i in range(len(xData)):
  20.         temp = yData[i]
  21.         for j in range(m+1):
  22.             b[j] = b[j] + temp
  23.             temp = temp*xData[i]
  24.         temp = 1.0
  25.         for j in range(2*m+1):
  26.             s[j] = s[j] + temp
  27.             temp = temp*xData[i]
  28.     for i in range(m+1):
  29.         for j in range(m+1):
  30.             a[i,j] = s[i+j]
  31.     return gaussPivot(a,b)
  32.  
  33. def stdDev(c,xData,yData):
  34.  
  35.     def evalPoly(c,x):
  36.         m = len(c) - 1
  37.         p = c[m]
  38.         for j in range(m):
  39.             p = p*x + c[m-j-1]
  40.         return p    
  41.  
  42.     n = len(xData) - 1
  43.     m = len(c) - 1
  44.     sigma = 0.0
  45.     for i in range(n+1):
  46.         p = evalPoly(c,xData[i])
  47.         sigma = sigma + (yData[i] - p)**2
  48.     sigma = sqrt(sigma/(n - m))
  49.     return sigma
  50. #//python/7406

回复 "Find the coefficients of the polynomial that fits "

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

captcha