random and np.random

本文演示了Python内置的random模块与NumPy的np.random模块生成随机数的方法,包括随机整数和浮点数。通过示例代码展示了两者的使用,并指出np.random.randint的参数与random.randint的区别,即np.random.randint的上限不包含在内。最后展示了如何生成多维随机整数数组。

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

random and np.random


def test_random():

    import random
    random.seed(1)

    # [1,5]的一个随机整数, params: low (include), high (include)
    print(random.randint(1, 5))  # 2

    # [0,1)的一个随机数
    print(random.random())  # 0.5692038748222122

    import numpy as np
    np.random.seed(1)

    # [0,1)的一个随机数
    print(np.random.random())  # 0.417022004702574
    print(np.random.random(size=[3]))

    """
    [7.20324493e-01 1.14374817e-04 3.02332573e-01]
    """
    print(np.random.random(size=[2,3]))
    """

    [[0.14675589 0.09233859 0.18626021]
     [0.34556073 0.39676747 0.53881673]]

    """
    # 随机整数
    # np.random.randint区别于random.randint
    # np.random.randint: low(include), high(exclude)
    # random.randint: low(include), high(include)
    print(np.random.randint(low=1, high=5, size=[2,4]))
    """
    [[3 2 3 1]
     [4 1 3 1]]
    """

    return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值