生成范围为[-1,1]的随机数数组 [英] Generating an array of random numbers in the range of [-1, 1]

查看:55
本文介绍了生成范围为[-1,1]的随机数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在2D数组中的Fortran中生成[-1,1]范围内的随机数.我知道,为了生成-1和1范围内的随机数,我必须将数字重新缩放为[0,2),但是我没有得到如何填充矩阵 x(10,10) randomReal .这是代码

I am trying to generate random numbers in the range of [-1, 1] in Fortran in a 2D array. I know that in order to generate random numbers in the range of -1 and 1, I have to rescale the numbers to [0,2) but I am not getting how to fill matrix x(10,10) with randomReal. Here is the code

program random
implicit none
real :: rnd, randomReal
real, dimension (10,10) :: x
integer :: L, i
L = 10         ! length of sequence
do i = 1, L
  call random_number(rnd)
  randomReal = 2*rnd-1
  print *, "random real = ", randomReal


end do
       write(*,*) (x(L,L), L=1,10) ! assign random numbers to matrix x
       call random_number(x)
    end program random

有人可以给我一些有关我的问题的建议吗?

Could anyone give me some suggestions on my problem?

推荐答案

根据随机可以在Fortran中进行数组/矩阵初始化(您读过吗?)可以

As per Random array / matrix intitialisation in Fortran (did you read that?) you can do

 xmin = -1
 xmax =  1
 call random_number(x)
 x = xmin + (xmax-xmin)*x

顺便说一句,数字将来自间隔 [-1,1),而不是 [-1,1] .

BTW, the numbers will be from interval [-1,1), not [-1,1].

这篇关于生成范围为[-1,1]的随机数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆