# ================================ # Steepest Descent Test Suite # ================================ tol_test <- 1e-4 # general tolerance for comparison # ---- Test 1: Simple 2D Quadratic ---- quad <- function(x) x[1]^2 + 2*x[2]^2 + x[1]*x[2] - 3*x[1] x0 <- c(0,0) res_quad <- sm.steepest_descent(quad, x0 = x0, verbose = TRUE) expected_quad <- c(12/7, -3/7) # Analytical solution if(res_quad$converged && all(abs(res_quad$x_min - expected_quad) < tol_test)){ cat("✅ Quadratic Test Passed! x_min =", paste(round(res_quad$x_min,6), collapse=", "), "| f_min =", round(res_quad$f_min,6), "\n\n") } else { cat("❌ Quadratic Test Failed! x_min =", paste(round(res_quad$x_min,6), collapse=", "), "| f_min =", round(res_quad$f_min,6), "\n\n") } # ---- Test 2: 1D Quadratic ---- f1d <- function(x) (x[1] - 5)^2 res_1d <- sm.steepest_descent(f1d, x0 = c(0), verbose = TRUE) if(res_1d$converged && abs(res_1d$x_min - 5) < tol_test){ cat("✅ 1D Quadratic Test Passed! x_min =", round(res_1d$x_min,6), "| f_min =", round(res_1d$f_min,6), "\n\n") } else { cat("❌ 1D Quadratic Test Failed! x_min =", round(res_1d$x_min,6), "| f_min =", round(res_1d$f_min,6), "\n\n") } # ---- Test 3: Rosenbrock Function ---- rosenbrock <- function(x) 100*(x[2]-x[1]^2)^2 + (1-x[1])^2 res_ros <- sm.steepest_descent(rosenbrock, x0 = c(-1.2, 1), verbose = TRUE) if(res_ros$converged && all(abs(res_ros$x_min - c(1,1)) < 1e-4)){ cat("✅ Rosenbrock Test Passed! x_min =", paste(round(res_ros$x_min,6), collapse=", "), "| f_min =", round(res_ros$f_min,6), "\n\n") } else { cat("❌ Rosenbrock Test Failed! x_min =", paste(round(res_ros$x_min,6), collapse=", "), "| f_min =", round(res_ros$f_min,6), "\n\n") } # ---- Test 4: High-Dimensional Quadratic ---- n <- 10 quad_n <- function(x) sum((1:n) * x^2) x0_n <- rep(1, n) res_nd <- sm.steepest_descent(quad_n, x0 = x0_n, verbose = FALSE) # Use a looser tolerance for high-dimensional optimization if(res_nd$converged && sqrt(sum(res_nd$x_min^2)) < 1e-4){ cat("✅ High-Dimensional Quadratic Test Passed! x_min ~ 0 | f_min =", round(res_nd$f_min,6), "\n\n") } else { cat("❌ High-Dimensional Quadratic Test Failed! x_min =", paste(round(res_nd$x_min,6), collapse=", "), "| f_min =", round(res_nd$f_min,6), "\n\n") } # ---- Test 5: Custom Step Size ---- res_fixed_alpha <- sm.steepest_descent(quad, x0 = x0, alpha = 0.1, verbose = TRUE) if(res_fixed_alpha$converged){ cat("✅ Fixed Step Size Test Passed! x_min =", paste(round(res_fixed_alpha$x_min,6), collapse=", "), "| f_min =", round(res_fixed_alpha$f_min,6), "\n\n") } else { cat("❌ Fixed Step Size Test Failed! x_min =", paste(round(res_fixed_alpha$x_min,6), collapse=", "), "| f_min =", round(res_fixed_alpha$f_min,6), "\n\n") }