(20181111)Fortran 产生随机数

参考: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)

参考: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)

 

 

 

 

 

 

 

 

 

 

 

 

  • 17
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值