Polynomial regression: Difference between revisions

Content added Content deleted
m (bug fix and made portable)
(Ada solution added)
Line 13: Line 13:




=={{header|Ada}}==
<ada>
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;

procedure Fitting is

function Fit (X, Y : Real_Vector) return Real_Vector is
A : Real_Matrix (0..2, X'Range); -- The plane
begin
for I in A'Range (2) loop
A (0, I) := 1.0;
A (1, I) := X (I);
A (2, I) := X (I)**2;
end loop;
return Solve (A * Transpose (A), A * Y);
end Fit;

C : Real_Vector :=
Fit
( (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0),
(1.0, 6.0, 17.0, 34.0, 57.0, 86.0, 121.0, 162.0, 209.0, 262.0, 321.0)
);
begin
Put (C (0), Aft => 3, Exp => 0);
Put (C (1), Aft => 3, Exp => 0);
Put (C (2), Aft => 3, Exp => 0);
end Fitting;
</ada>
The function Fit implements least squares approximation of a function defined in the points as specified by the arrays ''x''<sub>''i''</sub> and ''y''<sub>''i''</sub>. The basis &phi;<sub>''j''</sub> is 1, ''x'', ''x''<sup>2</sup>. The implementation is straightforward. First the plane matrix A is created. A<sub>ji</sub>=&phi;<sub>''j''</sub>(''x''<sub>''i''</sub>). Then the linear problem AA<sup>''T''</sup>''c''=A''y'' is solved. The result ''c''<sub>''j''</sub> are the coefficients. Constraint_Error is propagated when dimensions of X and Y differ or else when the problem is ill-defined.
Sample output:
<pre>
1.000 2.000 3.000
</pre>
=={{header|Fortran}}==
=={{header|Fortran}}==
{{libheader|LAPACK}}
{{libheader|LAPACK}}