如何更改此算法以在随机游走中合并多个粒子而不仅仅是一个粒子?

时间:2016-08-18 20:27:47

标签: fortran

如何在下面的程序中添加多个粒子?它只是一个简单的三维随机游走。

program RW3D

    implicit none

    integer :: x, y, z, i
    real :: P

    x = 0
    y = 0
    z = 0

    do i = 1, 100
       call random_number (p)

        write (1,*) i, x, y, z

        if (p .lt. 1.0/6) then
            x = x - 1
         else if (p .gt. 1.0/6 .lt. 2.0/6) then
            y = y - 1
         else if (p .lt. 3.0/6) then
            z = z - 1
         else if (p .lt. 4.0/6) then
            x = x + 1
         else if (p .lt. 5.0/6) then
            y = y + 1
         else
            z = z + 1
        end if

    end do

end program RW3D

1 个答案:

答案 0 :(得分:2)

最简单的方法:创建数组

   integer, parameter :: n = ...the number of particles

   integer :: x(n), y(n), z(n)
   integer :: i, j

.....

x = 0
y = 0
z = 0

do i = 1, 100
  do j = 1, n
   call random_number (p)

    if (p .lt. 1.0/6) then
        x(j) = x(j) - 1
     else if (p .gt. 1.0/6 .lt. 2.0/6) then
        y(j) = y(j) - 1

等等。

其他方法是为粒子创建派生类型

type particle
  integer :: x, y, z
end type

以及它们的数组

type(particle) :: particles(n)

我已经展示了大小为n的静态数组。当然你可以使用可分配的数组。

我没有包含任何输入/输出,因为您必须决定如何存储结果。

我不建议在1中使用单元号write(1,*)。低于10的单位通常用于特殊目的。使用10以上的数字。最好是使用Fortran 2008中的newunit=