Skip to content
The Chat Archive
claude-opus-4-20250514-thinking-16k· Anthropic LMArena Human Preference 140K

Create a subroutine in modern fortran. The subroutine shall calculate the minimum of a…

  1. User

    Create a subroutine in modern fortran. The subroutine shall calculate the minimum of a function f via newtons method. The subroutine should look like: subroutine mynewton(f, x) f shall be a generic subroutine that defines the user function like subroutine generic_f(x, r) where r is the value of the function f at the point x. Both the mynewton and the generic_f subroutines must handle scalar and vector valued versions for x and r. For now the Jacobian will be calculated via finite differences, a version where the Jacobian is provided by the user must not be considered. The FD jacobian shall be calculated in another subroutine to separate the code a bit.

  2. Assistant

    Here's a modern Fortran implementation of Newton's method that can handle both scalar and vector cases:

    module newton_module
        use iso_fortran_env, only: dp => real64
        implicit none
        
        private
        public :: mynewton
        
        ! Abstract interface for the user function
        abstract interface
            subroutine func_interface(x, r)
                import :: dp
                real(dp), intent(in) :: x(:)
                real(dp), intent(out) :: r(:)
            end subroutine func_interface
        end interface
        
        ! Parameters for Newton's method
        real(dp), parameter :: tol = 1.0e-10_dp
        real(dp), parameter :: eps = 1.0e-8_dp  ! For finite differences
        integer, parameter :: max_iter = 100
        
    contains
        
        subroutine mynewton(f, x)
            procedure(func_interface) :: f
            real(dp), intent(inout) :: x(:)
            
            real(dp), allocatable :: r(:), dx(:), jac(:,:)
            integer :: n, iter
            real(dp) :: norm_r
            
            n = size(x)
            allocate(r(n), dx(n), jac(n,n))
            
            do iter = 1, max_iter
                ! Evaluate function at current point
                call f(x, r)
                
                ! Check convergence
                norm_r = sqrt(sum(r**2))
                if (norm_r < tol) then
                    print *, 'Converged in', iter, 'iterations'
                    return
                end if
                
                ! Calculate Jacobian using finite differences
                call fd_jacobian(f, x, jac)
                
                ! Solve linear system: jac * dx = -r
                dx = -r
                call solve_linear_system(jac, dx)
                
                ! Update x
                x = x + dx
            end do
            
            print *, 'Warning: Maximum iterations reached without convergence'
            
        end subroutine mynewton
        
        subroutine fd_jacobian(f, x, jac)
            procedure(func_interface) :: f
            real(dp), intent(in) :: x(:)
            real(dp), intent(out) :: jac(:,:)
            
            real(dp), allocatable :: x_pert(:), r0(:), r_pert(:)
            integer :: i, j, n
            real(dp) :: h
            
            n = size(x)
            allocate(x_pert(n), r0(n), r_pert(n))
            
            ! Evaluate function at base point
            call f(x, r0)
            
            ! Calculate each column of Jacobian
            do j = 1, n
                x_pert = x
                h = eps * max(abs(x(j)), 1.0_dp)
                x_pert(j) = x(j) + h
                
                ! Forward difference
                call f(x_pert, r_pert)
                
                ! Fill j-th column of Jacobian
                jac(:,j) = (r_pert - r0) / h
            end do
            
        end subroutine fd_jacobian
        
        subroutine solve_linear_system(A, b)
            real(dp), intent(inout) :: A(:,:)
            real(dp), intent(inout) :: b(:)
            
            ! Simple Gaussian elimination with partial pivoting
            integer :: n, i, j, k, pivot_row
            real(dp) :: pivot_val, factor
            
            n = size(b)
            
            ! Forward elimination
            do k = 1, n-1
                ! Find pivot
                pivot_val = abs(A(k,k))
                pivot_row = k
                do i = k+1, n
                    if (abs(A(i,k)) > pivot_val) then
                        pivot_val = abs(A(i,k))
                        pivot_row = i
                    end if
                end do
                
                ! Swap rows if needed
                if (pivot_row /= k) then
                    call swap_rows(A, b, k, pivot_row)
                end if
                
                ! Eliminate column
                do i = k+1, n
                    factor = A(i,k) / A(k,k)
                    A(i,k:n) = A(i,k:n) - factor * A(k,k:n)
                    b(i) = b(i) - factor * b(k)
                end do
            end do
            
            ! Back substitution
            do i = n, 1, -1
                b(i) = (b(i) - sum(A(i,i+1:n) * b(i+1:n))) / A(i,i)
            end do
            
        end subroutine solve_linear_system
        
        subroutine swap_rows(A, b, i, j)
            real(dp), intent(inout) :: A(:,:), b(:)
            integer, intent(in) :: i, j
            real(dp), allocatable :: temp_row(:)
            real(dp) :: temp_val
            
            allocate(temp_row(size(A,2)))
            temp_row = A(i,:)
            A(i,:) = A(j,:)
            A(j,:) = temp_row
            
            temp_val = b(i)
            b(i) = b(j)
            b(j) = temp_val
        end subroutine swap_rows
        
    end module newton_module
    
    ! Wrapper module for scalar case
    module newton_scalar_wrapper
        use iso_fortran_env, only: dp => real64
        use newton_module
        implicit none
        
        abstract interface
            subroutine scalar_func_interface(x, r)
                import :: dp
                real(dp), intent(in) :: x
                real(dp), intent(out) :: r
            end subroutine scalar_func_interface
        end interface
        
    contains
        
        subroutine mynewton_scalar(f, x)
            procedure(scalar_func_interface) :: f
            real(dp), intent(inout) :: x
            
            real(dp) :: x_vec(1)
            
            x_vec(1) = x
            call mynewton(vector_wrapper, x_vec)
            x = x_vec(1)
            
        contains
            
            subroutine vector_wrapper(x_vec, r_vec)
                real(dp), intent(in) :: x_vec(:)
                real(dp), intent(out) :: r_vec(:)
                
                call f(x_vec(1), r_vec(1))
            end subroutine vector_wrapper
            
        end subroutine mynewton_scalar
        
    end module newton_scalar_wrapper
    
    ! Example usage
    program test_newton
        use iso_fortran_env, only: dp => real64
        use newton_module
        use newton_scalar_wrapper
        implicit none
        
        real(dp) :: x_scalar
        real(dp) :: x_vec(2)
        
        ! Test scalar case - find root of x^2 - 4 = 0
        print *, 'Scalar case: solving x^2 - 4 = 0'
        x_scalar = 3.0_dp
        call mynewton_scalar(scalar_func, x_scalar)
        print *, 'Solution:', x_scalar
        
        ! Test vector case - solve system of equations
        print *, ''
        print *, 'Vector case: solving system of equations'
        x_vec = [1.5_dp, 1.5_dp]
        call mynewton(vector_func, x_vec)
        print *, 'Solution:', x_vec
        
    contains
        
        subroutine scalar_func(x, r)
            real(dp), intent(in) :: x
            real(dp), intent(out) :: r
            
            r = x**2 - 4.0_dp
        end subroutine scalar_func
        
        subroutine vector_func(x, r)
            real(dp), intent(in) :: x(:)
            real(dp), intent(out) :: r(:)
            
            ! System: x1^2 + x2^2 - 4 = 0
            !         x1 - x2 = 0
            r(1) = x(1)**2 + x(2)**2 - 4.0_dp
            r(2) = x(1) - x(2)
        end subroutine vector_func
        
    end program test_newton
    

    This implementation provides:

    1. Generic Newton's method (mynewton) that works with vector inputs and outputs
    2. Finite difference Jacobian calculation in a separate subroutine (fd_jacobian)
    3. Scalar wrapper (mynewton_scalar) for convenience when working with scalar functions
    4. Linear system solver using Gaussian elimination with partial pivoting

    Key features:

    • The main mynewton subroutine works with arrays, making it general for both scalar and vector cases
    • The finite difference Jacobian is calculated in a separate subroutine as requested
    • The implementation uses modern Fortran features like abstract interfaces and modules
    • Includes convergence checking and iteration limits

    To use this for finding minima, you would pass the gradient of your objective function as the function f. For a scalar function of multiple variables, the gradient would be a vector function that you want to set to zero.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.