# ---- 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.quasi_newton(quad, x0 = x0, verbose = TRUE) expected_quad <- c(12/7, -3/7) stopifnot(res_quad$converged) stopifnot(all(abs(res_quad$x_min - expected_quad) < 1e-6)) cat("✅ Quadratic Test Passed! 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.quasi_newton(f1d, x0 = c(0), verbose = TRUE) stopifnot(res_1d$converged) stopifnot(abs(res_1d$x_min - 5) < 1e-6) cat("✅ 1D Quadratic Test Passed! x_min =", res_1d$x_min, " | f_min =", res_1d$f_min, "\n\n") # ---- Test 3: Rosenbrock function ---- rosenbrock <- function(x) 100*(x[2]-x[1]^2)^2 + (1-x[1])^2 res_ros <- sm.quasi_newton(rosenbrock, x0 = c(-1.2, 1), verbose = TRUE) stopifnot(res_ros$converged) stopifnot(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") # ---- Test 4: Custom Hessian ---- B0 <- diag(2) * 0.1 res_customB <- sm.quasi_newton(quad, x0 = x0, B0 = B0, verbose = TRUE) stopifnot(res_customB$converged) cat("✅ Custom Hessian Test Passed! x_min =", paste(round(res_customB$x_min,6), collapse = ", "), " | f_min =", round(res_customB$f_min,6), "\n\n") # ---- Test 5: Edge Case - Flat function ---- flat <- function(x) 0 # scalar output res_flat <- sm.quasi_newton(flat, x0 = c(0,0), verbose = TRUE) stopifnot(res_flat$converged) stopifnot(all(abs(res_flat$x_min - c(0,0)) < 1e-6)) cat("✅ Flat Function Test Passed! x_min =", paste(round(res_flat$x_min,6), collapse = ", "), " | f_min =", round(res_flat$f_min,6), "\n\n") # ---- Test 6: High-Dimensional Quadratic ---- n <- 10 quad_n <- function(x) sum((1:n) * x^2) x0_n <- rep(1, n) res_nd <- sm.quasi_newton(quad_n, x0 = x0_n, verbose = FALSE) stopifnot(res_nd$converged) stopifnot(all(abs(res_nd$x_min) < 1e-6)) cat("✅ High-Dimensional Quadratic Test Passed! x_min =", paste(round(res_nd$x_min,6), collapse = ", "), " | f_min =", round(res_nd$f_min,6), "\n\n")