Random 使用随机数删除文件的随机行。Fortran90
我一直在努力解决一个问题,所以如果有人能提供任何建议或例子,我将不胜感激。使用Fortran90 课程目的: 从文件中删除随机行,数量由我选择。我能想到的最好的方法是使用随机数来对应一个行号 它现在做什么: 每次生成新的随机数并将其输出到单独的文件中 问题: (1) 它不会生成与行号对应的整数。 (2) 我不知道如何使用这些数字从文件中删除行Random 使用随机数删除文件的随机行。Fortran90,random,fortran90,delete-row,Random,Fortran90,Delete Row,我一直在努力解决一个问题,所以如果有人能提供任何建议或例子,我将不胜感激。使用Fortran90 课程目的: 从文件中删除随机行,数量由我选择。我能想到的最好的方法是使用随机数来对应一个行号 它现在做什么: 每次生成新的随机数并将其输出到单独的文件中 问题: (1) 它不会生成与行号对应的整数。 (2) 我不知道如何使用这些数字从文件中删除行 program random1 implicit none integer :: i, seed, removed real :: r open (uni
program random1
implicit none
integer :: i, seed, removed
real :: r
open (unit=10,file='random.dat')
removed=5
call init_random_seed()
do i=1,removed
call random_number(r)
write(10,*) r
end Do
end program random1
subroutine init_random_seed()
integer :: i,n,clock
integer, dimension(:),allocatable :: seed
call random_seed(size=n)
allocate(seed(n))
call system_clock(count=clock)
seed=clock+37*(/(i-1,i=1,n)/)
call random_seed(put=seed)
deallocate(seed)
end subroutine
谢谢大家! 下面是答案的一些片段。首先是一些声明
integer :: num_lines ! number of lines in file
integer :: ix ! loop index variable
real :: fraction ! what fraction of lines are to be deleted
logical, dimension(:), allocatable :: lines_index
real, dimension(:), allocatable :: rands
现在是一些可执行文件
read(*,*) num_lines ! or figure it out some other way
read(*,*) fraction ! likewise
allocate(rands(num_lines)) ! no error checking
call random_number(rands)
allocate(lines_index(num_lines), source=rands<fraction) ! no error checking
请注意,我所采用的方法并不保证删除20%(或您设置的任何分数)行,只是这是最有可能删除的行数。如果要确保删除n
行,请执行以下操作
integer :: num_lines ! number of lines in file
integer :: ix, jx ! loop index variables
integer :: n ! number of lines to delete
integer, dimension(:), allocatable :: lines_index ! line numbers for deletion
real :: rand
read(*,*) n
allocate(del_ix(n))
do ix = 1,n
call random_number(rand)
lines_index(ix) = 1.0+num_lines*rand ! lines_index(ix) will be between 1 and num_lines
end do
这种方法不能保证同一行不会被多次选择删除,您必须编写一些代码来处理这种情况。然后继续:
do ix = 1, num_lines
read(infile,*) aline
if(any(lines_index==ix)) then
! do not write the line
else
write(outfile,*) aline
end if
end do
do ix = 1, num_lines
read(infile,*) aline
if(any(lines_index==ix)) then
! do not write the line
else
write(outfile,*) aline
end if
end do