一、c隨機數種子生成函數
c語言中的rand函數默認的隨機數生成是通過時間戳獲取的,因此每次生成的隨機數都是相同的。為了避免這種情況,我們需要引入隨機數種子。隨機數種子可用當前時間、進程ID以及用戶ID等元素生成。以下是一個生成隨機數種子的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", rand());
}
return(0);
}
上述程序中,我們利用了time函數來獲取當前時間並將其轉換成unsigned int,作為rand函數的種子。
二、rand函數生成36到37的隨機數
利用rand函數我們可以生成0到RAND_MAX(通常是32767)之間的隨機數。但這個範圍可能並不適合我們的需要,為此我們可以用一些算法來重新定義隨機數範圍。以下是生成36到37之間的隨機數的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", (rand() % 2) + 36);
}
return(0);
}
上述程序中,我們用rand函數生成0到1之間的隨機數,並將其加上36,得到36到37之間的隨機數。
三、用rand函數生成隨機數
通常情況下,我們使用rand函數生成隨機數的方式如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", rand());
}
return(0);
}
上述程序中,我們生成了5個隨機數。由於rand函數生成的隨機數較為分散,我們無法預測生成的具體數值。通過這種方式可以生成任何範圍內的隨機數。
四、python生成隨機數的函數
Python中生成隨機數的函數為random.random(),通過它我們可以生成0到1之間的隨機數。我們可以通過一定的算法改變生成隨機數的範圍。以下是生成0到10之間的隨機數的示例程序:
import random
def rand10():
return int(random.random() * 10)
print(rand10())
上面的代碼中,我們利用random.random()生成0到1之間的隨機數,並將其乘以10取整,得到0到10之間的隨機數。
五、rand函數生成20到50的隨機數
與前面的示例相似,我們可以通過rand函數生成任意範圍內的隨機數。以下是生成20到50之間的隨機數的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", (rand() % 31) + 20);
}
return(0);
}
上述程序中,我們生成一個0到30之間的隨機數,再將其加上20,得到20到50之間的隨機數。
六、rand函數生成10到20的隨機數
與前面的示例類似,以下是生成10到20之間的隨機數的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", (rand() % 11) + 10);
}
return(0);
}
上述程序中,我們生成一個0到10之間的隨機數,再將其加上10,得到10到20之間的隨機數。
七、rand函數生成60到85的隨機數
與前面的示例類似,以下是生成60到85之間的隨機數的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ){
printf("%d\n", (rand() % 26) + 60);
}
return(0);
}
上述程序中,我們生成一個0到25之間的隨機數,再將其加上60,得到60到85之間的隨機數。
八、matlab隨機數生成函數
Matlab中生成隨機數的函數為rand()或randn()。其中,rand()生成均勻分佈的隨機數,randn()生成正態分佈的隨機數。以下是生成10到20之間的隨機數的示例程序:
randi([10,20],1,5)
上述程序中,randi函數生成10到20之間的整數,1表示生成1行數據,5表示生成5個隨機數。
九、excel時間隨機數生成函數
Excel中生成隨機數的函數為RAND(),該函數返回0到1之間的隨機數。以下是生成隨機時間的示例程序:
=RAND()* (TIME(23,59,59)-TIME(0,0,0))+TIME(0,0,0)
上述函數中,RAND()生成0到1之間的隨機數,將其乘以1天的時間差,再加上當天的起點,即可生成隨機時間。
結語
通過上述示例,我們可以發現隨機數的生成有許多種方式,我們可以根據需要的隨機數範圍、分佈等情況選擇不同的方法。在實際的應用中,我們需要根據具體情況選擇合適的方法來生成隨機數。
原創文章,作者:FRKU,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/148543.html