Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

how to generate integer random number in fortran 90 in the range [0,5]?

I am kind of new in the fortran proramming. Can anyone please help me out with the solution. i am having a problem of generating integer random number in the range [0,5] in fortran random number using random_seed and rand

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To support the answer by Alexander Vogt, I'll generalize.

The intrinsic random_number(u) returns a real number u (or an array of such) from the uniform distribution over the interval [0,1). [That is, it includes 0 but not 1.]

To have a discrete uniform distribution on the integers {n, n+1, ..., m-1, m} carve the continuous distribution up into m+1-n equal sized chunks, mapping each chunk to an integer. One way could be:

call random_number(u)
j = n + FLOOR((m+1-n)*u)  ! We want to choose one from m-n+1 integers

As you can see, for the initial question for {0, 1, 2, 3, 4, 5} this reduces to

call random_number(u)
j = FLOOR(6*u)            ! n=0 and m=5

and for the other case in your comment {-1, 0, 1}

call random_number(u)
j = -1 + FLOOR(3*u)       ! n=-1 and m=1

Of course, other transformations will be required for sets of non-contiguous integers, and one should pay attention to numerical issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...