# 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 15: # x_grid = c( 1.2, 1.4, 1.6, 1.8 ) dy.dx = function(x, y){ 3*x^2 / ( 3*y^2 - 4 ) } h=0.1 res = euler(dy.dx, h=h, start=1, y0=0, end=1.8) 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=0, end=1.8) yhat_h2 = 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 ) rownames(A) = NULL R = cbind( c( 0.1, 0.05 ), A ) colnames(R) = c( 'h', sprintf( 'y(%.2f)', x_grid ) ) print('Problem 15:') print(R)