library(testthat) context("Newton's Method Optimization") # Test 1: Simple 2D quadratic function test_that("Newton's method finds minimum of 2D quadratic function", { f <- function(x) x[1]^2 + x[2]^2 res <- sm.newton(f, x0 = c(1, 1), tol = 1e-6, max_iter = 50, verbose = FALSE) # Check convergence expect_true(res$converged) # Check estimated minimum close to true minimum expect_equal(res$x_min, c(0, 0), tolerance = 1e-5) # Check function value at minimum expect_equal(res$f_min, 0, tolerance = 1e-5) # Iteration data frame should not be empty expect_true(nrow(res$iter_df) > 0) }) # Test 2: Shifted quadratic function test_that("Newton's method handles shifted quadratic function", { f <- function(x) (x[1]-3)^2 + (x[2]+2)^2 res <- sm.newton(f, x0 = c(0, 0), tol = 1e-6, max_iter = 50, verbose = FALSE) expect_true(res$converged) expect_equal(res$x_min, c(3, -2), tolerance = 1e-5) expect_equal(res$f_min, 0, tolerance = 1e-5) }) # Test 3: 1D quadratic function test_that("Newton's method works on 1D functions", { f <- function(x) (x[1]-5)^2 res <- sm.newton(f, x0 = c(0), tol = 1e-6, max_iter = 50, verbose = FALSE) expect_true(res$converged) expect_equal(res$x_min, 5, tolerance = 1e-5) expect_equal(res$f_min, 0, tolerance = 1e-5) }) # Test 4: Check verbose mode runs without error test_that("Newton's method verbose mode runs without error", { f <- function(x) x[1]^2 + x[2]^2 expect_error(res <- sm.newton(f, x0 = c(1, 1), verbose = TRUE), NA) }) # Test 5: Singular Hessian test_that("Newton's method stops on singular Hessian", { f <- function(x) x[1]^2 expect_error(sm.newton(f, x0 = c(0)), NA) # Should not error, Hessian is invertible })