You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran一维多项式积分代码结果与解析解不符问题排查

代码错误点

  • 多项式计算函数f(x)的返回值未初始化:Fortran中函数返回值不会默认初始化为0,你直接对f做累加操作,初始值是内存中的随机垃圾值,这是计算结果严重偏离的核心原因。
  • 多项式的系数与指数对应逻辑完全错误:你定义的numbers数组实际是多项式从最高次到常数项的系数序列,对应指数为7到0,但你代码中直接将numbers(i)同时作为系数和指数使用,计算逻辑完全不符合目标多项式。
  • 指数使用实型变量计算:你将指数存储在实型数组numbers中,用实型值作为幂运算的指数会引入不必要的精度误差,应当单独定义整型数组存储系数,再根据遍历下标直接计算对应指数。
  • 主程序未显式声明变量类型:虽然Fortran的I-N默认规则不会直接导致本次错误,但缺乏显式类型声明很容易埋下隐式类型错误的隐患。

修正后的可运行代码

program rectangularApproximation
    implicit none
    real :: a, b, eps, h, x, s, sprev, snext, f
    integer :: n, i

    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 program

real function f(x)
    implicit none
    real, intent(in) :: x
    integer :: i
    ! 系数按x^7到x^0的顺序排列
    integer, dimension(8), parameter :: coeff = [1,3,1,4,2,3,0,1]

    ! 初始化返回值
    f = 0.0
    do i = 1,8
        ! 第i个系数对应指数为 8 - i
        f = f + real(coeff(i)) * x ** (8 - i)
    end do
end function f

修正后在区间(1,2)、精度0.001下运行即可得到与解析解一致的结果。

内容的提问来源于stack exchange,提问作者gray KK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:45:01