Python工程师Java之路(g)随机数Java、Python、Scala

本文介绍了使用Java、Python及Scala等语言生成随机数的方法,包括生成随机整数、小数、正态分布随机数及随机数组等。此外,还提供了如何在程序中实现随机暂停的示例。

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

java

随机正态分布、随机整数

import java.util.Random;

class MyRandom {
    static Random random = new Random();

    static int nextInt(int bound) {
        // 随机[0,bound)的整数
        return random.nextInt(bound);
    }

    static double nextDouble() {
        // 返回随机均匀分布[0,1)的小数
        return random.nextDouble();
    }

    static double nextGaussian() {
        // 返回随机正态分布(平均值0.0,标准偏差1.0)的小数
        return random.nextGaussian();
    }
}

随机数

class MyRandom {

    static int randomInt(int bound) {
        // 随机[0,bound)的整数
        return (int) (Math.random() * bound);
    }

    static double random() {
        // 返回随机均匀分布[0,1)的小数
        return Math.random();
    }
}

随机睡眠

class RandomSleep {

    static int randomInt(int start, int end) {
        // 随机返回[start,end)的整数
        return (int) (start + Math.random() * (end - start));
    }

    static int randomInt(int end) {
        // 随机返回[0,end)的整数
        return (int) (Math.random() * end);
    }

    static double random() {
        // 随机返回[0,1)的小数
        return Math.random();
    }

    static void sleep(long millisecond) {
        try {
            Thread.sleep(millisecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static void sleepRandomly(int end) {
        try {
            Thread.sleep(randomInt(end));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Python

随机数

import random
# 随机0~1的小数
for _ in range(9):
    print(random.random())
# 随机[1,5]的整数
for _ in range(9):
    print(random.randint(1, 5))
import numpy
a = numpy.random.normal()
print(a)  # 随机数(正态分布)

随机数组

# 从正态分布中抽取样本(size:2行4列的数组)
numpy.random.normal(size=(2, 4))

# 从均匀分布中抽取样本(size:2行4列的数组)
numpy.random.uniform(low=0.0, high=1.0, size=(2, 4))

随机种子

import numpy
numpy.random.seed(2)
print(numpy.random.rand())  # 设置随机种子后,每次生成的随机数一样

Scala

val random: Random = new Random
// 从均匀分布中抽取[0,5)的样本
println(random.nextInt(5))
// 从高斯分布(均值0.0,标准偏差1.0)中抽取样本
println(random.nextGaussian())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值