亂數整理
亂數整理
C++
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand((unsigned int)time(NULL));
int r = rand(); //其值最小是 0,最大則為 RAND_MAX(32767)
}
C++的部分,有新方式可以處理
https://blog.gtwang.org/programming/cpp-random-number-generator-and-probability-distribution-tutorial/
C#
//https://docs.microsoft.com/zh-tw/dotnet/api/system.random?view=net-5.0
Random rnd = new Random(Guid.NewGuid().GetHashCode());
int n1 = rnd.Next(); // 傳回int數值,其範圍介於 0 - 2147483647,但不包含 2147483647(Int32.MaxValue)
int n2 = rnd.Next(700);//傳回int數值,其範圍介於 0 - 700,但不包含 maxValue
int n3 = rnd.Next(800, 7000); //傳回int數值,其範圍介於 800-7000,但不包含 7000
double n4 = rnd.NextDouble(); //傳回Double數值,其範圍介於0.0 - 1.0之間,但不包含1.0
python
import random
random.seed() #python 的亂數種子可以不必特別去設
x1 = random.random() #隨機浮點數,小於1,不包含1
x2 = random.uniform(-1, 3) #隨機浮點數,(-1 <= x < 3)
x3 = random.randrange(10) #隨機整數,(0 <= x < 10)
x4 = random.randrange(-10, 5) #隨機整數,資料範圍不包含 5 (-10 <= x < 5)
x5 = random.randint(-10, 5) #隨機整數,資料範圍包含 5 (a-10 <= x <= 5)
Lua
math.randomseed(os.time())
n1 = math.random() --產生[0,1) 隨機浮點數,不包含 1
n2 = math.random(10) --產生[1,10] 隨機整數,包含 10
n3 = math.random(-30, 30) --產生[-30,30] 隨機整數,包含30
留言
張貼留言