Okay, let's enhance the mynewton subroutine to accept an optional options parameter, which will allow users to specify maxIter, maxFunEvals, and tolX. We'll use real(8) for all floating-point numbers as requested.
First, we define a derived type for the options:
fortran
module newton_method
implicit none
private
public :: mynewton
public :: newton_options ! Make the options type public
! --- Derived type for Newton's method options ---
type :: newton_options
integer :: maxIter = 100 ! Maximum number of iterations
integer :: maxFunEvals = 1000 ! Maximum number of function evaluations
real(8) :: tolFunc = 1.0e-10_8 ! Tolerance for function value/norm convergence
real(8) :: tolX = 1.0e-8_8 ! Tolerance for change in x (step size) convergence
real(8) :: epsFD = 1.0e-8_8 ! Epsilon for finite differences
end type newton_options
! --- Abstract interfaces for scalar and vector functions ---
abstract interface
subroutine scalar_func(x, r)
real(8), intent(in) :: x
real(8), intent(out) :: r
end subroutine scalar_func
end interface
abstract interface
subroutine vector_func(x, r)
real(8), intent(in) :: x(:)
real(8), intent(out) :: r(:)
end subroutine vector_func
end interface
! --- Generic interface for mynewton ---
interface mynewton
module procedure mynewton_scalar
module procedure mynewton_vector
end interface mynewton
contains
! --- Newton's method for scalar functions ---
subroutine mynewton_scalar(f, x, options_in)
procedure(scalar_func) :: f
real(8), intent(inout) :: x
optional :: options_in
real(8) :: r, r_plus_h, dfdx, dx
integer :: iter
integer :: funEvalCount
type(newton_options) :: opts
! Assign user options or use defaults
if (present(options_in)) then
opts = options_in
else
! Defaults are already defined in the type definition
end if
funEvalCount = 0
do iter = 1, opts%maxIter
! --- Function Evaluation 1 (f(x)) ---
if (funEvalCount >= opts%maxFunEvals) then
print *, "Warning: Max function evaluations reached (scalar). Iter:", iter
return
end if
call f(x, r)
funEvalCount = funEvalCount + 1
! Check convergence on function value
if (abs(r) < opts%tolFunc) then
print *, 'Converged (f value) in ', iter, ' iterations'
return
end if
! --- Derivative Calculation using Finite Differences ---
real(8) :: h
h = opts%epsFD * max(abs(x), 1.0_8)
! --- Function Evaluation 2 (f(x+h)) ---
if (funEvalCount >= opts%maxFunEvals) then
print *, "Warning: Max function evaluations reached (scalar, f+h). Iter:", iter
return
end if
call f(x + h, r_plus_h)
funEvalCount = funEvalCount + 1
dfdx = (r_plus_h - r) / h
! Check if derivative is too small (potential division by zero or ill-conditioning)
if (abs(dfdx) < opts%epsFD / 10.0_8) then
print *, "Warning: Derivative too small at iteration", iter, ". Stopping."
return
end if
! Newton step calculation
dx = -r / dfdx
! Check convergence on step size (change in x)
if (abs(dx) < opts%tolX) then
print *, 'Converged (step size) in ', iter, ' iterations'
return
end if
! Update solution
x = x + dx
end do
print *, 'Warning: Max iterations reached without convergence (scalar)'
end subroutine mynewton_scalar
! --- Newton's method for vector functions ---
subroutine mynewton_vector(f, x, options_in)
procedure(vector_func) :: f
real(8), intent(inout) :: x(:)
optional :: options_in
real(8), allocatable :: r(:), dx(:), jac(:,:)
integer :: n, iter
real(8) :: norm_r
integer :: funEvalCount
type(newton_options) :: opts
! Assign user options or use defaults
if (present(options_in)) then
opts = options_in
else
! Defaults are already defined in the type definition
end if
n = size(x)
allocate(r(n), dx(n), jac(n,n))
funEvalCount = 0
do iter = 1, opts%maxIter
! --- Function Evaluation 1 (f(x)) ---
if (funEvalCount >= opts%maxFunEvals) then
print *, "Warning: Max function evaluations reached (vector, f). Iter:", iter
return
end if
call f(x, r)
funEvalCount = funEvalCount + 1
! Check convergence on function value norm
norm_r = sqrt(sum(r**2))
if (norm_r < opts%tolFunc) then
print *, 'Converged (f value norm) in ', iter, ' iterations'
return
end if
! --- Jacobian Calculation using Finite Differences ---
! Pass r (which is r0 for fd_jacobian) and the counter/limit
call fd_jacobian(f, x, r, jac, funEvalCount, opts%maxFunEvals, opts%epsFD)
! Solve linear system: jac * dx = -r
dx = -r
call solve_linear_system(jac, dx)
! Check convergence on step size norm
if (norm(dx) < opts%tolX) then
print *, 'Converged (step size norm) in ', iter, ' iterations'
return
end if
! Update solution
x = x + dx
end do
print *, 'Warning: Max iterations reached without convergence (vector)'
end subroutine mynewton_vector
! --- Finite difference derivative for scalar functions ---
! This helper is not directly called by mynewton_scalar anymore; the calculation is inlined.
! However, if it were a separate routine, it would look like this:
! subroutine fd_derivative(f, x, dfdx, funEvalCount, maxFunEvals_in, epsFD_in)
! ... (implementation as discussed in thought process) ...
! end subroutine fd_derivative
! --- Finite difference Jacobian for vector functions ---
subroutine fd_jacobian(f, x, r0, jac, funEvalCount, maxFunEvals_in, epsFD_in)
procedure(vector_func) :: f
real(8), intent(in) :: x(:)
real(8), intent(in) :: r0(:) ! Pass the base function value from the main loop
real(8), intent(out) :: jac(:,:)
integer, intent(inout) :: funEvalCount
integer, intent(in) :: maxFunEvals_in
real(8), intent(in) :: epsFD_in
real(8), allocatable :: r_pert(:), x_pert(:)
integer :: j, n
real(8) :: h
n = size(x)
allocate(r_pert(n), x_pert(n))
do j = 1, n
x_pert = x
h = epsFD_in * max(abs(x(j)), 1.0_8)
x_pert(j) = x(j) + h
! --- Function Evaluation for r_pert ---
if (funEvalCount >= maxFunEvals_in) then
print *, "Warning: Max function evaluations reached inside FD Jacobian calculation."
! This indicates the limit was hit during Jacobian computation itself.
! The main loop should ideally catch this first.
return
end if
call f(x_pert, r_pert)
funEvalCount = funEvalCount + 1
jac(:, j) = (r_pert - r0) / h
end do
deallocate(r_pert, x_pert)
end subroutine fd_jacobian
! --- Linear system solver using Gaussian elimination with partial pivoting ---
subroutine solve_linear_system(A, b)
real(8), intent(inout) :: A(:,:)
real(8), intent(inout) :: b(:)
integer :: n, i, j, k, pivot_row
real(8) :: factor, max_val
real(8), allocatable :: temp_row(:)
n = size(b)
allocate(temp_row(n))
! Forward elimination with partial pivoting
do k = 1, n-1
! Find pivot row
pivot_row = k
max_val = abs(A(k,k))
do i = k+1, n
if (abs(A(i,k)) > max_val) then
max_val = abs(A(i,k))
pivot_row = i
end if
end do
! Swap rows if necessary
if (pivot_row /= k) then
temp_row = A(k,:)
A(k,:) = A(pivot_row,:)
A(pivot_row,:) = temp_row
factor = b(k)
b(k) = b(pivot_row)
b(pivot_row) = factor
end if
! Check for near-zero pivot after pivoting
if (abs(A(k,k)) < 1.0e-15_8) then ! Use a small machine-epsilon-like value
print *, "Warning: Near-singular Jacobian matrix detected during elimination."
! Optionally, could stop or try a different solver.
end if
! Eliminate below
do i = k+1, n
factor = A(i,k) / A(k,k)
A(i,k+1:n) = A(i,k+1:n) - factor * A(k,k+1:n)
b(i) = b(i) - factor * b(k)
A(i,k) = 0.0_8 ! Explicitly set to zero for clarity
end do
end do
! Back substitution
do i = n, 1, -1
! Sum of A(i,j) * b(j) for j from i+1 to n
b(i) = (b(i) - dot_product(A(i,i+1:n), b(i+1:n))) / A(i,i)
end do
deallocate(temp_row)
end subroutine solve_linear_system
end module newton_method
! =====================================================================
! --- Example Usage Program ---
! =====================================================================
program test_newton_options
use newton_method
implicit none
real(8) :: x_scalar, x_vec(2)
type(newton_options) :: custom_opts
! --- Scalar Function Tests ---
print *, "--- Testing Scalar Functions ---"
print *, ""
! Test 1: Default options
print *, "Test 1: Solving scalar x^2 - 4 = 0 (default options)"
x_scalar = 3.0_8
call mynewton(scalar_f, x_scalar)
print *, "Solution:", x_scalar
print *
! Test 2: Custom options (fewer iterations, looser tolerances)
print *, "Test 2: Solving scalar x^2 - 4 = 0 (custom options)"
! Create a custom options object
custom_opts = newton_options(maxIter=5, maxFunEvals=20, tolFunc=1.0e-6_8, tolX=1.0e-5_8, epsFD=1.0e-6_8)
x_scalar = 3.0_8
call mynewton(scalar_f, x_scalar, custom_opts)
print *, "Solution:", x_scalar
print *
! Test 3: Custom options (stricter tolerances, more iterations)
print *, "Test 3: Solving scalar x^2 - 4 = 0 (stricter custom options)"
custom_opts = newton_options(maxIter=10, maxFunEvals=50, tolFunc=1.0e-12_8, tolX=1.0e-10_8, epsFD=1.0e-7_8)
x_scalar = 3.0_8
call mynewton(scalar_f, x_scalar, custom_opts)
print *, "Solution:", x_scalar
print *
print *, "----------------------------------"
print *, ""
! --- Vector Function Tests ---
print *, "--- Testing Vector Functions ---"
print *, ""
! Test 4: Default options for vector system
print *, "Test 4: Solving vector system:"
print *, " x^2 + y^2 = 4"
print *, " x - y = 0"
x_vec = [1.5_8, 1.5_8]
call mynewton(vector_f, x_vec)
print *, "Solution:", x_vec
print *
! Test 5: Custom options for vector system
print *, "Test 5: Solving vector system (custom options)"
custom_opts = newton_options(maxIter=10, maxFunEvals=60, tolX=1.0e-7_8)
x_vec = [1.5_8, 1.5_8]
call mynewton(vector_f, x_vec, custom_opts)
print *, "Solution:", x_vec
print *
print *, "----------------------------------"
contains
! --- Example Scalar Function ---
! Finds root of f(x) = x^2 - 4
subroutine scalar_f(x, r)
real(8), intent(in) :: x
real(8), intent(out) :: r
r = x**2 - 4.0_8
end subroutine scalar_f
! --- Example Vector Function ---
! System:
! f1(x,y) = x^2 + y^2 - 4 = 0
! f2(x,y) = x - y = 0
subroutine vector_f(x, r)
real(8), intent(in) :: x(:)
real(8), intent(out) :: r(:)
r(1) = x(1)**2 + x(2)**2 - 4.0_8
r(2) = x(1) - x(2)
end subroutine vector_f
end program test_newton_options
Explanation of Changes:
newton_options Derived Type:
A new type :: newton_options is defined within the newton_method module.
It includes maxIter, maxFunEvals, tolFunc, tolX, and epsFD as its components.
Default values are assigned directly in the type definition, making the options parameter truly optional.
The newton_options type itself is made public so it can be used in the main program.
Generic mynewton Interface:
The interface mynewton block remains the same, directing calls to mynewton_scalar or mynewton_vector.
Modified mynewton_scalar and mynewton_vector:
Both subroutines now accept an optional argument options_in of type newton_options.
Inside each subroutine, an internal opts variable of type newton_options is declared.
An if (present(options_in)) block checks if the user provided their own options. If so, opts is assigned the user's values. Otherwise, opts retains the default values defined in the newton_options type.
The hardcoded limits and tolerances (max_iter, tol, eps) are replaced with opts%maxIter, opts%tolFunc, opts%tolX, and opts%epsFD respectively.
A funEvalCount integer variable is introduced in both routines to track the number of times the user's function f is called.
Checks like if (funEvalCount >= opts%maxFunEvals) are placed before function calls to enforce the limit.
The fd_jacobian subroutine is modified to accept funEvalCount, maxFunEvals_in, and epsFD_in to manage the function evaluation count and parameters.
fd_jacobian Modifications:
It now accepts funEvalCount (intent(inout)), maxFunEvals_in, and as arguments.
This revised structure provides a more flexible and configurable Newton's method implementation.
epsFD_in
It increments funEvalCount each time it calls the user-provided function f for calculating finite differences.
A check if (funEvalCount >= maxFunEvals_in) is added before calling f inside fd_jacobian as a safeguard.
Example Usage Program:
The test_newton_options program now includes demonstrations of calling mynewton both with and without the optional options argument, showing how to create and pass a custom newton_options variable.
All floating-point literals are suffixed with _8 (e.g., 1.0_8) to ensure they are treated as real(8).