# I use the function knn.reg for simple comparisons below: # if( !require('FNN') ){ install.packages("FNN", dependencies=TRUE, repos='http://cran.rstudio.com/') } library(FNN) source('euler.R') # Problem 17: # x_grid = seq( 1.0, 3.0, by=0.5 ) dy.dx = function(x, y){ ( y^2 + 2*x*y ) / ( 3 + x^2 ) } h=0.1 res = euler(dy.dx, h=h, start=1, y0=2, end=3.0) yhat_h1 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) h=0.05 res = euler(dy.dx, h=h, start=1, y0=2, end=3.0) yhat_h2 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) h=0.025 res = euler(dy.dx, h=h, start=1, y0=2, end=3.0) yhat_h3 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) h=0.01 res = euler(dy.dx, h=h, start=1, y0=2, end=3.0) yhat_h4 = knn.reg( as.matrix( res\$xs ), y=res\$ys, test=as.matrix( x_grid ), k=1, algorithm='brute' ) A = rbind( yhat_h1\$pred, yhat_h2\$pred, yhat_h3\$pred, yhat_h4\$pred ) rownames(A) = NULL R = cbind( c( 0.1, 0.05, 0.025, 0.01 ), A ) colnames(R) = c( 'h', sprintf( 'y(%.2f)', x_grid ) ) print('Problem 17:') print(R)