我最近遇到了一个我从未听说过的称为“函数 vector ”的术语。我需要定义一个“函数 vector ”来解决非线性代数方程组。 《数字食谱》中有一个名为“newt”的例程可以执行此操作。在C++中,数值食谱为我定义了一类新的函数 vector ,因此我所要做的就是使用提供的库调用nr3.h。有人知道如何在Fortran90 / 95/03/08中执行此操作(这些标准中的任何一项都对我有效)?我想知道,因为我不精通C++,所以我宁愿在Fortran中工作。

C++的代码可以在这里找到:
http://numerical.recipes/forum/showthread.php?t=1703&highlight=403

注意代码中的函数“VecDoub y(3)”。这不是C++固有的(我不认为)。但是,由于C++中可以定义新类,因此VecDoub是在C++中定义的。有没有办法在Fortran中做到这一点?

谢谢。

最佳答案

正如@Peter在评论中所说,“功能 vector ”没有什么特别的。 VecDoub只是普通的double型 vector ,而vecfunc实际上是 vector 的函数。然后,newt只是一个接受 vector 和 vector 函数的过程。

在fortran中最接近的等效项是这样的:

program vector_functions
  implicit none
  logical :: check
  integer :: i
  double precision :: x(3) = [0, 5, 7], y(3)

  print *, 'Initial guess: ', x
  print *, 'Calling newt...'
  call newt(x, check, vecfunc)
  if(check) then
    print *, 'Check is true (convergence to a local minimum).'
    print *, 'Try another initial guess.'
  else
    print *, 'Check is false (a \"normal\" return).'
  end if
  print *, 'Solution from newt: ', x
  y = vecfunc(x)
  print *, 'Value of the solution vector: ', y

contains
  function vecfunc(x) result(y)
    double precision, intent(in) :: x(:)
    double precision :: y(size(x))
    y(1) = x(1) * x(2) * x(3) - 6
    y(2) = x(1) * x(1) * x(2) + x(2) * x(2) * x(3) + x(3) * x(3) * x(1) - 23
    y(3) = exp(x(1) + x(2) + x(3)) - 403
  end
  subroutine newt(x, check, f)
    double precision, intent(inout) :: x(:)
    logical, intent(out) :: check
    interface
      function f(a)
        double precision, intent(in) :: a(:)
        double precision :: f(size(a))
      end
    end interface
    ! custom implementation of newt here...
  end
end

10-04 22:38
查看更多