姬長信(Redy)

修正割线法算法


我下面的代码使用secant方法查找分析函数的根.解析函数f必须在我的代码的函数部分中指定.下面的代码运行良好,没有编译错误.但是,对于我要解决的问题,我不知道解析函数f.

取而代之的是,我以数字方式计算函数,并将其存储为数组.现在,我想应用我的代码来查找此函数的根源.那么,如何修改代码,使输入不是解析函数,而只是我已经计算出的数组?

我的工作代码如下,我假设我只需要修改最后一个调用函数f的部分,我不确定该怎么做.谢谢!

program main
  implicit none 
  real :: a = 1.0, b = -1.0
  integer :: m = 8
  interface
  function f(x)
  real, intent(in) :: x
  end function
  end interface

  call secant(f,a,b,m)
  end program main

  subroutine secant(f,a,b,m)
  implicit none
  real, intent(in out) :: a,b
  integer, intent(in) :: m
  real :: fa, fb, temp
  integer :: n
  interface
  function f(x)
  real, intent(in) :: x
  end function f
  end interface

  fa = f(a)
  fb = f(b)
  if (abs(fa) >  abs(fb)) then
     temp = a
     a = b
     b = temp
     temp = fa
     fa = fb
     fb = temp
  end if
  print *,"    n        x(n)         f(x(n))"
  print *," 0 ", a, fa    
  print *," 1 ", b, fb
  do n = 2,m
     if (abs(fa) >  abs(fb)) then
        temp = a
        a = b
        b = temp
        temp = fa
        fa = fb
        fb = temp
     end if
     temp = (b - a)/(fb - fa)
       b = a
     fb = fa
     a = a - fa*temp
     fa = f(a)
     print *,n,a,fa
  end do   
  end subroutine secant

  real function f(x)
  implicit none 
  real, intent(in) :: x
  f = x**5 + x**3 + 3.0 !analytic form of a function, I don't actually have this though, I just have the function stored as an array
  end function f