在Erlang中生成随机数

2009-03-09

Erlang中生成随机数要使用random模块,首先讲讲主要用到的函数:

seed(A1, A2, A3) -> ran()

Types: A1 = A2 = A3 = int()

Seeds random number generation with integer values in the process dictionary, and returns the old state.One way of obtaining a seed is to use the BIF now/0:


{A1,A2,A3} = now(),
random:seed(A1, A2, A3),

uniform()-> float()

Returns a random float uniformly distributed between 0.0 and 1.0, updating the state in the process dictionary.

uniform(N) -> int()

Types: N = int()

Given an integer N >= 1, uniform/1 returns a random integer uniformly distributed between 1 and N, updating the state in the process dictionary.

例子:

-module(test).

-export([start/0]).

%设定状态并开始生成随机数

start() ->

{A1,A2,A3}=now(),

random:seed(A1,A2,A3),

generateRandom(4).

%生成N个随机数

generateRandom(0) -> ok,

generateRandom(N) ->

io:fwrite(”~p/n”,[random:uniform(10)]),

generateRandom(N-1).


另附一段C生成随机数的代码:

#include

#include

#include

int main(){

int i;

srand(time(NULL));

for(i=0;i<4;i++){

printf(”%d : %d\n”,i,rand());

}

}

感觉和Erlang大同小异~~

M-OSCAR | Powered by Blogger | Entries (RSS) | Comments (RSS) | Designed by MB Web Design | XML Coded By Cahayabiru.com