(20181111)Fortran 产生随机数

版权声明:未经作者同意,不得擅自转载。 https://blog.csdn.net/sinat_32602421/article/details/83963763

参考:http://blog.sciencenet.cn/blog-588243-502012.html

*********************************************************************

1)生成一个0-1之间的随机数

先用random_seed (),系统根据日期和时间随机地提供种子,使得随机数更随机了。

random_number(x) 产生一个0到1之间的随机数(x可以是向量),但是每次总是那几个数。
 

program random
   implicit none
   real :: x
   call random_seed ()     ! 系统根据日期和时间随机地提供种子
   call random_number (x)  ! 每次的随机数就都不一样了
   write(*,*) x  !输出一个0——1之间的随机数
   stop
end program random

**********************************20181112************************************************

2)产生一个任意区间的随机数:

program random_ex
implicit none
real::randNum
real::lbound,ubound
real::my_random!调用函数时,也要声明函数数据类型real,不然出错
call random_seed()!库函数,生成随机数前调用
randNum=my_random(1.0,10.0)
write(*,*) randNum
end

function my_random (lbound,ubound)
implicit none
 real :: lbound,ubound
 real :: len
 real :: my_random
 real :: t
 
 
 len=ubound-lbound  !计算范围大小
 call random_number(t)  !t是0-1之间的随机数
 my_random=lbound+len*t

 return
end  

3)产生一个任意区间的随机数组:(当函数返回值为一个数组是,此时需要在主函数中定义一个函数接口interface)

扫描二维码关注公众号,回复: 4425766 查看本文章

参考:https://mp.csdn.net/postedit/83963544

program interface_ex
   implicit none
   
interface !定义函数func的使用接口
function random10(lbound,ubound)
implicit none
real::lbound,ubound
real::random10(10)!返回值是一个数组
end function
end interface

real::a(10)
call random_seed()!库函数,生成随机数前调用
a=random10(1.0,10.0)!生成10个0-10之间的随机数
write(*,'(10F6.2)') a
    end
    
    
    !编写函数random10(lbound,ubound),
    !返回10个范围在(lbound,ubound)之间的随机数
function random10(lbound,ubound)
implicit none
real::lbound,ubound
real::random10(10)

real::t,len
integer i
len=ubound-lbound
do i=1,10
    call random_number(t)!t是0-1之间的随机数
    random10(i)=lbound+len*t  !把t转换为lbound和ubound范围
end do
return
    end function

将上面的(lbound,ubound)输为(0.0,1.0)就可以得到0-1之间的随机数;

program interface_ex
   implicit none
   
interface !定义函数func的使用接口
function random10(lbound,ubound)
implicit none
real::lbound,ubound
real::random10(10)!返回值是一个数组
end function
end interface

real::a(10)
call random_seed()!库函数,生成随机数前调用
!a=random10(1.0,10.0)!生成10个0-10之间的随机数
a=random10(0.0,1.0)!生成10个0-1之间的随机数
write(*,'(10F6.2)') a
    end
    
    
    !编写函数random10(lbound,ubound),
    !返回10个范围在(lbound,ubound)之间的随机数
function random10(lbound,ubound)
implicit none
real::lbound,ubound
real::random10(10)

real::t,len
integer i
len=ubound-lbound
do i=1,10
    call random_number(t)!t是0-1之间的随机数
    random10(i)=lbound+len*t  !把t转换为lbound和ubound范围
end do
return
    end function

4)如何产生正态分布的随机数??(unresolved)

猜你喜欢

转载自blog.csdn.net/sinat_32602421/article/details/83963763