JSFiddle - React, Tailwind, and code Playground
by ipeshev
HTML
<table id="table">
<thead>
<tr><th>X values</th><th>Y values</th><th>Corrections</th></tr>
</thead>
<tbody data-bind="foreach: points">
<tr>
<td data-bind="text: x"></td>
<td data-bind="text: y"></td>
<td data-bind="text: corrections"></td>
</tr>
</tbody>
</table>
CSS
td {
border:1px solid black;
}
JavaScript
function getValue(x,u){
return (x+u)/(x+u+1);
}
function RungeKutta(iter,h,x0,y0,fx){
var k1,k2,
xi = x0 ,yi = y0;
var result = [];
result.push(yi);
for( i=0; i<iter; i++){
k1 = h*fx(xi,yi);
k2 = h*fx((xi+h),yi+k1);
yi = yi + (k1+k2)/2;
result.push(yi)
xi=xi+h;
}
return result;
}
function predictorFX(yp,yc,h,xc){
return yp + 2*h*getValue(xc,yc);
}
function correctorFX(yp,yc,h,xc){
return yc + h/2*(getValue(xc+h,yp)+getValue(xc,yc));
}
var y = [];
var corrected = [];
function PredictorCorrectorTemplate(epsilon,x0,y0,xe,steps){
var h = (xe-x0)/steps,maxCorrections= 3,c,temp;
var diff,ycorr,ypred,yprevcorr,y=[],points = [] ;
y[0]=y0;
y[1] = RungeKutta(2,h,x0,y0,getValue)[1];
yc=y0,xc=x0;
points.push({x:xc,y:yc,corrections:0});
xc= xc+h;
for(i=1;i<=steps;i++){
ypred = predictorFX(y[i-1],y[i],h,xc);
yprevcorr = ypred;
c=0;
do {
ycorr = correctorFX(yprevcorr,y[i],h,xc);
temp = yprevcorr;
yprevcorr = ycorr;
corrected.push(ycorr);
c++;
} while((Math.abs(temp-yprevcorr)>epsilon)&&(c<=maxCorrections));
y[i+1] = ycorr;
points.push({x:xc,y:ycorr,corrections:c});
corrected = [];
xc= xc+h;
}
return points;
}
ko.applyBindings( {
points: PredictorCorrectorTemplate(0.00001,0,0,0.7,28),
},document.getElementById('table'));