if-statement - 即使满足条件,程序也不会在 Fortran 中进入 if 循环
问题描述
这是未按预期运行的代码部分。我必须包含一些老式的“暂停”语句来查明错误位置。
iteration_index = 1
y_refined = y_current + (0.5d0*dx*(dydx_predictor + dydx_refined_corrector)) ! Solution corresponds to i = 2, i.e., the refined Heun's method.
relative_percent_error = 100.d0*(abs((y_refined - y_next)/y_refined)) ! Calculation of relative percentage error. This is NOT true error.
if (relative_percent_error > heun_percent_tolerance) then
iteration_index = iteration_index + 1
print*, 'first loop enter', x_next, relative_percent_error, iteration_index
pause
if (iteration_index < max_heun_number) then
y_next = y_refined
call dydx(x_next, y_next, dydx_refined_corrector)
y_refined = y_current + (0.5d0*dx*(dydx_predictor + dydx_refined_corrector))
relative_percent_error = 100.d0*(abs((y_refined - y_next)/y_refined))
print*, 'second loop enter', x_next, relative_percent_error, iteration_index
pause
end if
end if
输出如下:
first loop enter 1.0000000000000000 6.7763423346068707 2
PAUSE
To resume execution, type go. Other input will terminate the job.
go
RESUMED
second loop enter 1.0000000000000000 1.6658644147581094 2
PAUSE
To resume execution, type go. Other input will terminate the job.
go
RESUMED
first loop enter 2.0000000000000000 6.6615482639252761 2
PAUSE
To resume execution, type go. Other input will terminate the job.
的值为heun_percent_tolerance
0.01 和max_heun_number
15。我希望执行进入第二个 if 循环进行更多迭代,直到达到最大限制 15,但似乎代码跳转到下一个x_next
值 2。
我什至尝试将这两个条件结合起来If (cond1 .and. cond2)
,但也没有用。
解决方案
您的代码中没有循环!IF
不是循环!除非你放一个实际的循环,否则它不会重复执行。
If you want to loop some code while a condition is still valid, use a DO WHILE
loop or a DO
loop with EXIT
.
do while (relative_percent_error > heun_percent_tolerance)
iteration_index = iteration_index + 1
print*, 'first loop enter', x_next, relative_percent_error, iteration_index
pause
if (iteration_index < max_heun_number) then
y_next = y_refined
call dydx(x_next, y_next, dydx_refined_corrector)
y_refined = y_current + (0.5d0*dx*(dydx_predictor + dydx_refined_corrector))
relative_percent_error = 100.d0*(abs((y_refined - y_next)/y_refined))
print*, 'second loop enter', x_next, relative_percent_error, iteration_index
pause
end if
end do
Note the code is still likely incorrect, you will have to restructure it, but the point is that you need an actual DO
loop and not just an IF
condition. An IF
is not a loop.
推荐阅读
- c# - 当我启动 asp.net 应用程序时,IIS Express 会启动正在运行的站点的副本
- ios - 我可以在没有访问证书、标识符和配置文件权限的情况下部署到 App Store Connect 吗?
- java - 将 Java 对象实例化为传递的对象引用
- powershell - Powershell:浏览目录中的所有文件(PDF)并根据前 6 个字节中写入的内容移动它们
- python - triggering_frequency 只能与写入 BigQuery 的 FILE_LOADS 方法一起使用
- c# - 属性规范中奇怪的歧义(两个 using 指令)
- mimekit - 无法从 MimeMessage 解析 tnef 部分
- php - 在 Imgur PHP 上上传视频
- magento-1.9 - 如何使用 Whatsapp 发送 Mag::Log 错误?
- java - 使现有 API 更加 RESTful