Polynomial regression: Difference between revisions

→‎{{header|Ada}}: Modified to arbitrary degree
(Ada solution added)
(→‎{{header|Ada}}: Modified to arbitrary degree)
Line 16:
<ada>
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
 
function Fit (X, Y : Real_Vector; N : Positive) return Real_Vector is
procedure Fitting is
A : Real_Matrix (0..N, X'Range); -- The plane
 
begin
function Fit (X, Y : Real_Vector) return Real_Vector is
for I in A : Real_Matrix'Range (0..2, X'Range); -- The planeloop
for J in A'Range (1) loop
begin
for I in A'Range (2J, I) loop:= X (I)**J;
A (0, I) := 1.0;
A (1, I) := X (I);
A (2, I) := X (I)**2;
end loop;
end Fitloop;
return Solve (A * Transpose (A), A * Y);
end Fit;
end Fit;
</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'', <sup>''xj''<sup>2</sup>, ''j''=0,1,..,''N''. 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.
===Example===
<ada>
with Fit;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
 
procedure Fitting is
C : constant 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),
A (0, I) := 1.0;2
);
begin
Line 42 ⟶ 47:
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}}==
{{libheader|LAPACK}}