tests/testthat/test-newton.R

test_that("Newton converges on known roots and records true updates", {
  f <- function(x)x^2-2
  a <- f |> vc_newton(x0=1)
  expect_true(a$converged)
  expect_identical(a$status,"converged")
  expect_equal(a$estimate,sqrt(2),tolerance=1e-8)
  expect_equal(a$iterations$n,seq_len(nrow(a$iterations))-1L)
  for(i in seq_len(nrow(a$iterations)-1L))
    expect_equal(a$iterations$x[i+1],a$iterations$x[i]-a$iterations$fx[i]/a$iterations$dfx[i])
  expect_true(all(a$iterations$residual==abs(a$iterations$fx)))
  expect_true(all(vapply(a$derivative_diagnostics,function(d)d$reliable,logical(1))))
  b <- vc_newton(f,1,df=function(x)2*x)
  expect_true(b$converged)
  expect_equal(b$estimate,a$estimate,tolerance=1e-8)
  a <- vc_newton(function(x)cos(x)-x,1)
  expect_true(a$converged)
  expect_equal(a$estimate,.7390851332,tolerance=1e-8)
})

test_that("Newton accepts initial roots before a derivative and diagnoses failure", {
  a <- vc_newton(function(x)x^2,0,df=function(x)stop("must not evaluate"))
  expect_true(a$converged)
  expect_equal(nrow(a$iterations),1)
  expect_length(a$derivative_diagnostics,0)
  expect_identical(vc_newton(function(x)x^2+1,0)$status,"derivative_too_small")
  expect_identical(vc_newton(function(x)x^3-2*x+2,0)$status,"cycle_detected")
  expect_identical(vc_newton(function(x)x^2-2,1,max_iter=0)$status,"max_iter")
  expect_identical(vc_newton(function(x)x^2-2,1,max_iter=1)$status,"max_iter")
  expect_identical(vc_newton(function(x)x+1,0,df=function(x)NA_real_)$status,"nonfinite_derivative")
  expect_identical(vc_newton(function(x)x+1,0,df=function(x)1e300)$status,"stagnation")
  a <- vc_newton(log,10)
  expect_identical(a$status,"nonfinite_evaluation")
  expect_equal(a$estimate,10)
  expect_true(a$rejected_trial$x<0)
  expect_identical(vc_newton(function(x)abs(x)+.1*x+1,0)$status,"derivative_unreliable")
  a <- vc_newton(function(x)abs(x)+1,0)
  expect_false(a$converged)
  expect_identical(a$status,"derivative_too_small")
  a <- vc_newton(function(x)1e308,0,df=function(x)1e-308,derivative_tol=0)
  expect_identical(a$status,"nonfinite_step")
  expect_false(a$converged)
})

test_that("Newton controls and invalid functions are validated", {
  expect_error(vc_newton(1,0),"function")
  expect_error(vc_newton(sin,Inf),"finite real")
  expect_error(vc_newton(sin,0,df=1),"df")
  expect_error(vc_newton(sin,0,max_iter=1.5),"integer")
  expect_error(vc_newton(sin,0,h=0),"h")
  expect_error(vc_newton(sin,0,x_tol=-1),"x_tol")
  expect_error(vc_newton(sin,0,f_tol=Inf),"f_tol")
  expect_error(vc_newton(sin,0,derivative_tol=NA_real_),"derivative_tol")
  expect_error(vc_newton(sin,0,method="other"))
  expect_error(vc_newton(function(x)c(1,2),0),"finite real")
})

Try the vectorialcalculus package in your browser

Any scripts or data that you put into this service are public.

vectorialcalculus documentation built on Nov. 17, 2026, 1:09 a.m.