我同意Vladamir F.的观点,但是...
为了帮助您寻找更好的随机数,可以考虑使用C++中相对较新的C++11伪随机数生成器。其中包括了梅森旋转算法和许多其他算法。这是一个非常完善的系统。我认为您可以通过以下两种方式来测试这些序列:
- 从Fortran调用一个小型的C++实用程序来为您生成一堆随机数或
- 通过ISO_C_BINDING将随机数生成器绑定到Fortran。
我更喜欢第二种方法,因为绑定有点棘手,所以我准备了一个示例。文件如下:
- cxx11_rand.h和cxx11_rand.cpp,它们定义了对随机数生成器的调用
- c_rand.cpp,它调用C++函数中的C函数
- f_rand_M.f90,它将C函数绑定到Fortran
- f_main.f90,它使用模块函数在[0,1)范围内生成10个随机数。
cxx11_rand.h
#ifndef CXX11_RAND_H
#define CXX11_RAND_H
void cxx11_init();
double cxx11_rand();
#endif
cxx11_rand.cpp
#include <algorithm>
#include <cstdio>
#include <memory>
#include <random>
#include <set>
#include <vector>
#include <chrono>
#include <thread>
#include <iostream>
#include "cxx11_rand.h"
static std::unique_ptr<std::uniform_real_distribution<>> dist;
static std::unique_ptr<std::mt19937_64> eng;
void cxx11_init(){
eng = std::unique_ptr<std::mt19937_64>( new std::mt19937_64(std::random_device{}()) );
dist = std::unique_ptr< std::uniform_real_distribution<> >( new std::uniform_real_distribution<>(0.0,1.0) );
}
double cxx11_rand(){
return (*dist)( *eng );
}
c_rand.cpp
#include "cxx11_rand.h"
#ifdef __cplusplus
extern "C" {
#endif
void c_init(){
cxx11_init();
}
double c_rand(){
return cxx11_rand();
}
#ifdef __cplusplus
}
#endif
f_rand_M.f90
module f_rand_M
implicit none
interface
subroutine fi_init() bind(C, name="c_init")
end subroutine
real(C_DOUBLE) function fi_rand() bind(C, name="c_rand")
use ISO_C_BINDING, only: C_DOUBLE
end function
end interface
contains
subroutine f_init()
call fi_init()
end subroutine
real(C_DOUBLE) function f_rand()
use ISO_C_BINDING, only: C_DOUBLE
f_rand = fi_rand()
end function
end module
f_main.f90
program main
use f_rand_M
implicit none
integer :: i
call f_init()
do i=1,10
write(*,*)f_rand()
end do
end program
你可以使用以下GNU命令进行编译/链接
echo "compiling objects"
g++ -c --std=c++11 cxx11_rand.cpp c_rand.cpp
gfortran -c f_rand_M.f90
echo "building & executing fortran main"
gfortran f_main.f90 f_rand_M.o c_rand.o cxx11_rand.o -lstdc++ -o f_main.exe
./f_main.exe
您的输出应该像这样(当然,具有不同的随机数字--此处的种子是从“熵源”选择的,例如墙上时间)。
compiling objects
building & executing fortran main
0.47439556226575341
0.11177335018127127
0.10417488557661241
0.77378163596792404
0.20780793755332663
0.27951447624366532
0.66920698086955666
0.80676663600103105
0.98028384008440417
0.88893587108730432
我在 Mac 上使用 GCC 4.9 进行测试。