-
Notifications
You must be signed in to change notification settings - Fork 192
/
polyFit.py
55 lines (45 loc) · 1.29 KB
/
polyFit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
## module polyFit
''' c = polyFit(xData,yData,m).
Returns coefficients of the polynomial
p(x) = c[0] + c[1]x + c[2]x^2 +...+ c[m]x^m
that fits the specified data in the least
squares sense.
sigma = stdDev(c,xData,yData).
Computes the std. deviation between p(x)
and the data.
'''
from numpy import zeros
from math import sqrt
from gaussPivot import *
def polyFit(xData,yData,m):
a = zeros((m+1,m+1))
b = zeros(m+1)
s = zeros(2*m+1)
for i in range(len(xData)):
temp = yData[i]
for j in range(m+1):
b[j] = b[j] + temp
temp = temp*xData[i]
temp = 1.0
for j in range(2*m+1):
s[j] = s[j] + temp
temp = temp*xData[i]
for i in range(m+1):
for j in range(m+1):
a[i,j] = s[i+j]
return gaussPivot(a,b)
def stdDev(c,xData,yData):
def evalPoly(c,x):
m = len(c) - 1
p = c[m]
for j in range(m):
p = p*x + c[m-j-1]
return p
n = len(xData) - 1
m = len(c) - 1
sigma = 0.0
for i in range(n+1):
p = evalPoly(c,xData[i])
sigma = sigma + (yData[i] - p)**2
sigma = sqrt(sigma/(n - m))
return sigma