How do I retain precision for a Fortran MPI program in a portable way?

前端 未结 3 1988
独厮守ぢ
独厮守ぢ 2020-12-11 01:36

I have a Fortran program where I specify the kind of the numeric data types in an attempt to retain a minimum level of precision, regardless of what compiler is

3条回答
  •  情歌与酒
    2020-12-11 02:07

    Use the Fortran 2008 intrinsic STORAGE_SIZE to determine the number bytes that each number requires and send as bytes. Note that STORAGE_SIZE returns the size in bits, so you will need to divide by 8 to get the size in bytes.

    This solution works for moving data but does not help you use reductions. For that you will have to implement a user-defined reduction operation. If that's important to you, I will update my answer with the details.

    For example:

    program main
    
       use mpi
    
       implicit none
    
       integer, parameter :: rsp = selected_real_kind(16)
       integer :: err
       integer :: rank
    
       real(rsp) :: real_var
    
       call MPI_Init(err)
       call MPI_Comm_rank(MPI_COMM_WORLD,rank,err)
    
       if (rank.eq.0) then
          real_var = 1.123456789012345
          call MPI_Send(real_var,storage_size(real_var)/8,MPI_BYTE,1,5,MPI_COMM_WORLD,err)
       else
          call MPI_Recv(real_var,storage_size(real_var)/8,MPI_BYTE,0,5,MPI_COMM_WORLD,&
             MPI_STATUS_IGNORE,err)
       end if
    
       print *, rank, real_var
    
       call MPI_Finalize(err)
    
    end program main
    

    I confirmed that this change corrects the problem and the output I see is:

       0   1.12345683574676513672      
       1   1.12345683574676513672  
    

提交回复
热议问题