【问题标题】:Matlab to Python conversion of rand()Matlab 到 Python 的 rand() 转换
【发布时间】:2016-08-19 08:13:20
【问题描述】:

在 Matlab 中我有以下内容:

duration = 20
n=5
times = rand(1,n)*duration;

变量“times”给出了一个 1×n 矩阵,其中填充了 0 到 1 之间的随机数,然后乘以 20。这将产生一组 5 个介于 0 到 20 之间的数字。

现在我想在 Python 中实现同样的功能,什么是等价的? 我尝试了以下方法:

times = random.uniform(1,durations,n)  %% or times = random.uniform(1,20,5)

但我得到这个错误:

TypeError: uniform() 只需要 3 个参数(给定 4 个)

这对我来说没有意义,因为我似乎只给了它 3 个参数。

【问题讨论】:

    标签: python matlab random code-conversion


    【解决方案1】:

    random.uniform 只接受随机数的上限和下限。您将需要调用 random.uniform n 次来创建随机值列表。

    values = [random.uniform(0, 20) for _ in range(5)]
    

    或者,您可以使用numpy.random.rand 来执行此操作,类似于 MATLAB,该函数将返回一个 numpy 数组。

    import numpy as np
    values = np.random.rand(1, 5) * 20
    

    如果您要将大量代码从 MATLAB 转换为 Python,建议使用 numpy 而不是使用标准数据类型,因为它的计算速度和与 MATLAB 相似的行为。

    【讨论】:

    • 非常感谢您的解释和解决方案!确实,这行得通,我尝试了 numpy 版本!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2014-01-23
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2019-01-30
    相关资源
    最近更新 更多