source: Sophya/trunk/SophyaLib/NTools/linfit.cc@ 517

Last change on this file since 517 was 514, checked in by ansari, 26 years ago

elimination des OVector/OMatrix au profit des TVector/TMatrix cmv 25/10/99

File size: 2.4 KB
Line 
1#include "machdefs.h"
2#include "peida.h"
3#include "linfit.h"
4
5double LinFit(const Vector& x, const Vector& y, int nf, double (*f)(int, double),
6 Vector& c)
7{
8 int n = x.NElts();
9 if (n != y.NElts()) THROW(sizeMismatchErr);
10
11 Matrix fx(nf, n);
12 for (int i=0; i<nf; i++)
13 for (int j=0; j<n; j++)
14 fx(i,j) = f(i,x(j));
15
16 return LinFit(fx,y,c);
17}
18
19
20
21double LinFit(const Matrix& fx, const Vector& y, Vector& c)
22{
23 int n = y.NElts();
24 if ( n != fx.NCol()) THROW(sizeMismatchErr);
25
26 int nf = fx.NRows();
27
28 Matrix a(nf,nf);
29
30 for (int j=0; j<nf; j++)
31 for (int k=j; k<nf; k++)
32 a(j,k) = a(k,j) = fx.Row(j) * fx.Row(k);
33
34 c = fx * y;
35
36 if (Matrix::GausPiv(a,c) == 0) THROW(singMatxErr);
37
38 double xi2 = 0;
39
40 for (int k=0; k<n; k++) {
41 double x = 0;
42 for (int i=0; i<nf; i++)
43 x += c(i) * fx(i,k);
44 x -= y(k);
45 xi2 += x*x;
46 }
47 return xi2;
48}
49
50
51
52double LinFit(const Vector& x, const Vector& y, const Vector& errY2, int nf,
53 double (*f)(int, double), Vector& c, Vector& errC)
54{
55 int n = x.NElts();
56 if (n != y.NElts()) THROW(sizeMismatchErr);
57
58 Matrix fx(nf, n);
59 for (int i=0; i<nf; i++)
60 for (int j=0; j<n; j++)
61 fx(i,j) = f(i,x(j));
62
63 return LinFit(fx,y,errY2,c,errC);
64}
65
66
67double LinFit(const Matrix& fx, const Vector& y, const Vector& errY2,
68 Vector& c, Vector& errC)
69{
70 int n = y.NElts();
71 if ( n != errY2.NElts()) THROW(sizeMismatchErr);
72 if ( n != fx.NCol()) THROW(sizeMismatchErr);
73
74 int nf = fx.NRows();
75
76 Matrix a(nf,nf);
77
78 c.Realloc(nf);
79 errC.Realloc(nf);
80
81 for (int j=0; j<nf; j++)
82 for (int k=j; k<nf; k++) {
83 double x=0;
84 for (int l=0; l<n; l++)
85 x += fx(j,l) * fx(k,l) / errY2(l); // Matrice a inverser
86 a(j,k) = a(k,j) = x;
87 }
88
89 Matrix d(nf,nf+1);
90 for (int k=0; k<nf; k++) {
91 double x=0;
92 for (int l=0; l<n; l++)
93 x += fx(k,l) * y(l) / errY2(l); // Second membre 1ere colonne
94 d(k,0) = x;
95 for (int m=1; m<=nf; m++)
96 d(k,m) = (k==m) ? 1 : 0; // Reste second membre = Id.
97 }
98
99 if (Matrix::GausPiv(a,d) == 0) THROW(singMatxErr);
100
101 for (int l=0; l<nf; l++) {
102 c(l) = d(l,0); // Parametres = 1ere colonne
103 errC(l) = d(l,l+1); // Erreurs = diag inverse.
104 }
105
106 double xi2 = 0;
107
108 for (int jj=0; jj<n; jj++) {
109 double x = 0;
110 for (int ii=0; ii<nf; ii++)
111 x += c(ii) * fx(ii,jj);
112 x -= y(jj);
113 xi2 += x*x/errY2(jj);
114 }
115 return xi2;
116}
Note: See TracBrowser for help on using the repository browser.