gpt4 book ai didi

fortran - 无法在此 Fortran 代码中输入 f(x) 值?

转载 作者:行者123 更新时间:2023-12-02 15:20:59 25 4
gpt4 key购买 nike

    program prob_1
implicit real*8(a-h, o-z)
f(x) = x**2-cos(x)
df(x) = 2*x+sin(x)
x0 = 0, x1 = 1
do i = 1, 3
if (f((x0+x1)/2) < 0)
x0 = (x0+x1)/2
else
x1 = (x0+x1)/2
end do
print *,"x = ", x
end program

我刚刚开始使用 Fortran 90。现在我正在使用 Code::blocks 但我不知道错误到底出现在哪一行。

我猜问题是f((x0+x1)/2) < 0但实际上不知道真正的错误是什么。这里有什么问题吗?

最佳答案

请注意,语句函数(OP 使用的函数定义)已过时。

B.3.4 Statement functions

  1. Statement functions are subject to a number of non intuitive restrictions and are a potential source of error because their syntax is easily confused with that of an assignment statement.
  2. The internal function is a more generalized form of the statement function and completely supersedes it.

source: F2018 Standard

此外,符号 REAL*8 或任何该形式的内容从未成为任何 Fortran 标准的一部分(请参阅 here ):

我建议将代码重写为:

program prob_1
implicit none
double precision :: x1,x0
integer :: i
x0 = 0; x1 = 1
do i = 1, 3
if (f((x0+x1)/2.0D0) < 0) then
x0 = (x0+x1)/2.0D0
else
x1 = (x0+x1)/2.0D0
endif
end do
print *,"x = ", (x0+x1)/2.0D0
contains
function f(x)
double precision, intent(in) :: x
double precision :: f
f = x**2-cos(x)
end function f
function df(x)
double precision, intent(in) :: x
double precision :: df
df = 2.0D0*x+sin(x)
end function df
end program

关于fortran - 无法在此 Fortran 代码中输入 f(x) 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59188629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com