source('utils.R') # 3.1-1: # xs = seq( -5, +5, length.out=100 ) fs = xs^2 - 2 * xs - 2 plot( xs, fs, type='l', xlab='x', ylab='x^2 - 2 x - 2' ) abline(h=0, col='black') grid() truth = polyroot( c( -2, -2, 1 ) ) truth = Re(truth) # For the left-most root (negative one): # bm_res = bisection_method(-2, 0, function(x){x^2-2*x-2}, xtol=1.e-2) rf_res = regula_falsi(-2, 0, function(x){x^2-2*x-2}, xtol=1.e-2) mrf_res = modified_regula_falsi(-2, 0, function(x){x^2-2*x-2}, xtol=1.e-2) print(sprintf('Truth= %f; Bisection= %f; Regula Falsi= %f; Modified Regula Falsi= %f', truth[1], bm_res[1], rf_res[1], mrf_res[1])) # For the right-most root (positive one): # bm_res = bisection_method(1, 4, function(x){x^2-2*x-2}, xtol=1.e-2) rf_res = regula_falsi(1, 4, function(x){x^2-2*x-2}, xtol=1.e-2) mrf_res = modified_regula_falsi(1, 4, function(x){x^2-2*x-2}, xtol=1.e-2) print(sprintf('Truth= %f; Bisection= %f; Regula Falsi= %f; Modified Regula Falsi= %f', truth[2], bm_res[1], rf_res[1], mrf_res[1])) # 3.1-3: # xs = seq( 0, +3, length.out=100 ) fs = xs^3 - 2 * xs - 1 plot( xs, fs, type='l', xlab='x', ylab='x^3 - 2 x - 1' ) abline(h=0, col='black') grid() truth = polyroot( c( -1, -2, 0, 1 ) ) truth = Re(truth) secant_res = secant_method(1, 2, function(x){x^3-2*x-1}, xtol=1.e-2) print(sprintf('Truth= %f; Secant= %f', truth[3], secant_res[1])) # 3.1-6: # fn_1 = function(x){ 1/(3*x-1) } xs = seq( 0, +1, length.out=100 ) fs = fn_1(xs) plot( xs, fs, type='l', xlab='x', ylab='1/(3x-1)' ) abline(h=0, col='black') grid() fn_2 = function(x){ cos(10*x) } xs = seq( 0, +1, length.out=100 ) fs = fn_2(xs) plot( xs, fs, type='l', xlab='x', ylab='cos(10*x)' ) abline(h=0, col='black') grid() fn_3 = function(x){ if(x>=0.3){ 1.0 }else{ -1.0 } } xs = seq( 0, +1, length.out=100 ) fs = rep(1.0, length(xs)) fs[xs<0.3] = -1.0 plot( xs, fs, type='l', xlab='x', ylab='step function' ) abline(h=0, col='black') grid() # 3.1-7: # root_fn = function(x){ exp(2*x) - exp(x) - 2 } root_fn_prime = function(x){ 2*exp(2*x) - exp(x) } xs = seq( 0, +1, length.out=100 ) fs = root_fn(xs) plot( xs, fs, type='l', xlab='x', ylab='exp(2x) - exp(x) - 2' ) abline(h=0, col='black') grid() newton_res = newtons_method(0.6, root_fn, root_fn_prime, xtol=1.e-4) print(sprintf('Newton= %f', newton_res[1])) # 3.1-8: # root_fn = function(x){ 4*sin(x) - exp(x) } xs = seq( 0, 0.5, length.out=100 ) fs = root_fn(xs) plot( xs, fs, type='l', xlab='x', ylab='4sin(x) - exp(x)') abline(h=0, col='black') grid() secant_res = secant_method(0, 0.5, root_fn, xtol=1.e-4) print(sprintf('Secant= %f', secant_res[1])) # 3.1-9: # root_fn = function(x){ 2*x^3 - 3*x - 4 } xs = seq( 0, 3, length.out=100 ) fs = root_fn(xs) plot( xs, fs, type='l', xlab='x', ylab='2x^3 - 2 x - 1') abline(h=0, col='black') grid() truth = polyroot( c(-4, -3, 0, 2 ) ) bm_res = bisection_method(0, 3, root_fn, xtol=1.e-3) print(sprintf('Truth= %f; Bisection= %f', truth[3], bm_res[1]))