# I use the function knn.reg to evaluate the numerical solution at a fixed grid of points # if( !require('FNN') ){ install.packages('FNN', dependencies=TRUE, repos='http://cran.rstudio.com/') } library(FNN) source('improved_euler.R') t0 = 0 y0 = 1 t1 = 0.4 # Where do we want to evaluate the solution: # x_grid = seq( t0, t1, by=0.1 ) # The improved Euler method: # dy.dt = function(t, y){ 2*t + exp(-t*y) } h=0.05 res = improved_euler(dy.dt, h=h, start=t0, y0=y0, end=t1) ie_yhat_h1 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) h=0.025 res = improved_euler(dy.dt, h=h, start=t0, y0=y0, end=t1) ie_yhat_h2 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) h=0.0125 res = improved_euler(dy.dt, h=h, start=t0, y0=y0, end=t1) ie_yhat_h3 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) A = rbind( ie_yhat_h1\$pred, ie_yhat_h2\$pred, ie_yhat_h3\$pred ) rownames(A) = NULL R = cbind( c( 0.05, 0.025, 0.0125 ), A ) colnames(R) = c( 'h', sprintf( 'y(%.2f)', x_grid ) ) print('Problem 4 (Improved Euler):') print(R)