【问题标题】:Integral of 1D array in FortranFortran中一维数组的积分
【发布时间】:2021-10-21 03:38:57
【问题描述】:

任务是编写计算多项式函数积分的代码。我所附图像中显示的函数id。我写了代码并编译了,答案就出来了。但是,它与解析解完全不同。代码:

     program rectangularApproximation
     
     write(*,*) "Input values of a ,b and eps"
     read(*,*) a,b,eps



1    continue
     n=1000
     h=(b-a)/n
     s=0.0
     do i=1,n
         x=a+h*i
         s=s+f(x)*h
     enddo

     sprev=s
     n=10*n

     h=(b-a)/n

     s=0.0

     do i=1,n
         x=a+h*i
         s=s+f(x)*h
     enddo

     snext=s

     if (abs(sprev-snext)<eps) then
         write(*,*) snext,n
         stop
     end if
         goto 1

     write(*,*) s
     end
       real function f(x)

            implicit none
            real, intent(in)    :: x
            integer             :: i
            real, dimension(8) :: numbers
            numbers = (/1,3,1,4,2,3,0,1 /)


            do i = 1,8
                f = f + numbers(i) * x**(numbers(i))
            end do
        end function

运行代码得到的结果为588189248(区间(a,b)为(1,2),我选择epsillon=0.001)解析解如下:

解析解的答案是 169.256 。我的代码可能出了什么问题?

【问题讨论】:

    标签: fortran integral calculus


    【解决方案1】:

    你的多项式代码是错误的:

                do i = 1,8
                    f = f + numbers(i) * x**(numbers(i))
                end do
    

    应该是这样的

                do i = 1,8
                    f = f + numbers(i) * x**i
                end do
    

    【讨论】:

    • 哦,我更正了,现在它显示 2.16091034E+09 :(
    • 在执行计算之前你也永远不会将 f 归零
    • 您将不得不调试打印一些中间值。我编写的 Python 代码反映了你的代码,我得到了 n=1000 的 168.965 和 n=10000 的 169.225。函数的单个值范围从15到598,我不知道你是怎么得到20亿的。
    • 调试打印语句可以是你的朋友。通常只需要在循环中将它们执行到 I=2。
    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多