几种语言的随机数生成方法总结

本文介绍了C/C++、Java、C#、Lua和Python五种编程语言中随机数的生成方法,包括设置随机数种子、生成指定范围内的随机整数和浮点数等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 .C与C++

int rand(void);

返回[0, 32767)之间的一个伪随机整数,其中RAND_MAX = 32767

void srand(unsigned int seed);

设置随机序列种子

经常用时间做种子:

srand((unsigned)time(NULL));

 

下面是生成在一个指定区间 [range_min, range_max) 的随机整数的方法:

int u = (double)rand() / (RAND_MAX+1) * (range_max - range_min) + range_min;

 

Windows下有更安全的版本:

errno_t rand_s(unsigned int * randomValue);

2. Java

使用Math.random()得到 [0,1) 区间的随机数

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("你想要的范围最大数:");
        java.util.Scanner input = new java.util.Scanner(System.in);
        double n= input.nextDouble();
        for(int i = 0; i<5; i++)
        {
            System.out.println(Math.random()*n+1);
        }
    }
}

3. C#

使用类Random

无参构造函数默认使用与时间相关的种子实例化一个Random类对象;

也可以指定种子作为构造函数参数实例化,Random(int seed);

(1)  public virtual int Next();

返回非负伪随机数,范围在 [0, Int32.MaxValue)

(2) public virtual int Next(int maxValue);

返回非负整数,范围在[0, maxValue)。要求maxValue非负

(3) public virtual int Next(int minValue, int maxValue);

返回[minValue, maxValue)之间的带符号的随机整数

若minValue == maxValue, 返回该值

若minValue > maxValue 抛出异常AugumentOutOfRange

(4) public virtual double NextDouble();

返回[0.0, 1.0)之间的随机double

(5) public virtual void NextBytes(byte[] buffer);

填充字节数组,取值范围是[0, 255]

// Example of the Random.Next( ) methods.
using System;

public class RandomNextDemo  
{
    // Generate random numbers with no bounds specified.
    static void NoBoundsRandoms( int seed )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, no bounds:", seed );
        Random randObj = new Random( seed );

        // Generate six random integers from 0 to int.MaxValue.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", randObj.Next( ) );
        Console.WriteLine( );
    }

    // Generate random numbers with an upper bound specified.
    static void UpperBoundRandoms( int seed, int upper )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, upper bound = {1}:", 
            seed, upper );
        Random randObj = new Random( seed );

        // Generate six random integers from 0 to the upper bound.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", randObj.Next( upper ) );
        Console.WriteLine( );
    }

    // Generate random numbers with both bounds specified.
    static void BothBoundsRandoms( int seed, int lower, int upper )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, lower = {1}, " +
            "upper = {2}:", seed, lower, upper );
        Random randObj = new Random( seed );

        // Generate six random integers from the lower to 
        // upper bounds.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", 
                randObj.Next( lower, upper) );
        Console.WriteLine( );
    }

    static void Main( )
    {	
        Console.WriteLine(                 
            "This example of the Random.Next( ) methods\n" +
            "generates the following output.\n" );
        Console.WriteLine(                 
            "Create Random objects all with the same seed and " +
            "generate\nsequences of numbers with different " +
            "bounds. Note the effect\nthat the various " +
            "combinations of bounds have on the sequences." );
    	
        NoBoundsRandoms( 234 );

        UpperBoundRandoms( 234, Int32.MaxValue );
        UpperBoundRandoms( 234, 2000000000 );
        UpperBoundRandoms( 234, 200000000 );

        BothBoundsRandoms( 234, 0, Int32.MaxValue );
        BothBoundsRandoms( 234, Int32.MinValue, Int32.MaxValue );
        BothBoundsRandoms( 234, -2000000000, 2000000000 );
        BothBoundsRandoms( 234, -200000000, 200000000 );
        BothBoundsRandoms( 234, -2000, 2000 );
    }
}

/*
This example of the Random.Next( ) methods
generates the following output.

Create Random objects all with the same seed and generate
sequences of numbers with different bounds. Note the effect
that the various combinations of bounds have on the sequences.

Random object, seed = 234, no bounds:
 2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2147483647:
 2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2000000000:
 1947533580   954563751   662424922  1007613896  1707392518   101943116

Random object, seed = 234, upper bound = 200000000:
  194753358    95456375    66242492   100761389   170739251    10194311

Random object, seed = 234, lower = 0, upper = 2147483647:
 2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, lower = -2147483648, upper = 2147483647:
 2034812868   -97573602  -724936960    16350718  1519113864 -1928562472

Random object, seed = 234, lower = -2000000000, upper = 2000000000:
 1895067160   -90872498  -675150156    15227793  1414785036 -1796113767

Random object, seed = 234, lower = -200000000, upper = 200000000:
  189506716    -9087250   -67515016     1522779   141478503  -179611377

Random object, seed = 234, lower = -2000, upper = 2000:
       1895         -91        -676          15        1414       -1797
*/

4. Lua

(1)  math.randomseed(n)

接受整数作为随机序列的种子,常用的是os.time

(2)  math.random( [n [, m]] )

无参数时产生[0, 1)之间的随机浮点数

有一个整数作为参数时,产生[1, n]之间的随机整数

有2个整数作为参数时,产生[n, m]之间的随机整数

seed相差越小,随机序列越相似。

 

5. Python

需要import库random,有如下几个常用的方法:

(1) random.random()

返回[0, 1)的浮点数

(2) random.randint(a, b)

返回[a, b]闭区间的整数

(3) random.uniform(a, b)

返回区间[a, b) 或 [a, b]的浮点数

>>> print(random.random())
0.1662079568337036
>>> help(random.random)
random(...) method of random.Random instance
    random() -> x in the interval [0, 1).

>>> print(random.randint(10, 20))
15
>>> help(random.randint)
randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

>>> print(random.uniform(2,5))
2.0082116592913324
>>> help(random.uniform)
uniform(a, b) method of random.Random instance
    Get a random number in the range [a, b) or [a, b] depending on rounding.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值