gpt4 book ai didi

fortran - 来自转置数组的源分配

转载 作者:行者123 更新时间:2023-12-04 21:02:31 25 4
gpt4 key购买 nike

我试图了解我在代码中遇到的错误。当尝试使用数组的转置分配数组时,我在代码中使用了带有 source=transpose(original_array) 的分配语句。但是,使用这种方法我没有得到预期的结果。似乎索引关闭了一个并且跳过了源数组的第一行。

例子:

program testalloc
real*8, allocatable :: a(:, :)
real*8, allocatable :: b(:, :)

allocate(b(2, 3))
b(1, :) = [1, 2, 3]
b(2, :) = [4, 5, 6]
call printmat(b)

a = transpose(b)
call printmat(a) ! Good

deallocate(a)
allocate(a(3, 2), source=transpose(b))
call printmat(a) ! Bad

deallocate(a)
allocate(a(3, 2))
a = transpose(b)
call printmat(a) ! Good

contains

subroutine printmat(mat)
real*8, intent(in) :: mat(:, :)
integer :: i

write(*,*) 'print'
do i = 1, size(mat, 1)
write(*,*) mat(i, :)
end do
end subroutine

end program

这使
 print
5.0000000000000000 3.0000000000000000
6.0000000000000000 0.0000000000000000
3.2114266979681025E-322 5.0000000000000000

对于使用 gfortran(gcc 版本 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04))而不是转置的原始数组编译后的源分配。我在这里做错了什么还是编译器错误?

最佳答案

来源分配

allocate(a(3, 2), source=transpose(b))

是一个有效的。为 a 指定的形状与源表达式 transpose(b) 相同.结果, a取给定表达式的值。

编译器给出不同的结果是不正确的。输出例程不是这里的罪魁祸首。

gfortran 8 似乎给出了预期的输出。

有趣的是,对于 gfortran 7,如果 b 出现预期结果本身不可分配。

关于fortran - 来自转置数组的源分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132482/

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