Maple One Coursework - Curve Fitting
The following code is to define the goodfit()
procedure, It takes as it's input; a list of points, the list being of varying length. After finding how many points there are in the given list and assigning it to the variable 'length
', it sets a matrix, 'mat
' to the relevant number of rows and columns.
It then loops through each row or the matrix and within that loops through each column adding the co-efficient in it's correct place and then the y
element to the end of that row, (using the method of curve fitting).
Using the gaussjord()
method of the linalg package, the polynomial is created recursively in y
. This can then be tested.
goodfit() code:-
goodfit := proc(pts::list) local length, result, element, mat, i, j, y; length := nops(pts); with(linalg); mat:= matrix(length, (length+1)); for j from 1 to length do for i from 1 to length do element := pts[j][1]^(i-1); mat[j, i] := element; od; mat[j, (length+1)]:= pts[j][2]; od; result:= gaussjord(mat); y:= 0; for j from 1 to length do y:= y + result[j, (length+1)]*(x^(j-1)); od; end:
Testing:-
The code was tested using the points (1,23), (2,5), (3,-5), (4,10) and (100,2), plotted from x=0
to x=100
. (See Plot A)
> y:= goodfit([[1, 23], [2, -5], [3, -5], [4, 10], [100, 2]]); > plot([y, [[1, 23], [2, -5], [3, -5], [4, 10], [100, 2]]], x=0..100, color=[grey, black], style=[line, point]);
On plot A it is quite hard to see the individual points, using a graph from x=0
to x=7
, it is clearer to observe that the procedure worked: (See Plot B)
> plot([y, [[1,23],[2,-5],[3,-5],[4,10],[100,2]]], x=0..7, color=[grey, black], style=[line, point]);