【问题标题】:python - np.random.random round up to 1 decimalpython - np.random.random 四舍五入到小数点后 1
【发布时间】:2020-06-21 13:47:26
【问题描述】:

尝试使用np.random.random生成数字:

for portfolio in range(2437):
    weights = np.random.random(3)
    weights /= np.sum(weights)

    print(weights)

它按预期工作:

[0.348674 0.329747 0.321579]
[0.215606 0.074008 0.710386]
[0.350316 0.589782 0.059901]
[0.639651 0.025353 0.334996]
[0.697505 0.171061 0.131434]
.
.
.
.

但是,我如何更改数字,以使每行限制为 1 个小数,例如:

[0.1 0.2 0.7]
[0.2 0.2 0.6]
[0.5 0.4 0.1]
.
.
.
.

【问题讨论】:

  • 注意,如果你真的想对它们进行四舍五入,然后在四舍五入后使用它们,你会极大地改变数字的分布。 F.e.,对于 bin [0.0...0.05) 中的所有数字,您将得到 0.0,bin 宽度为 0.05。但是0.1 的可能性是两倍,因为它将为 bin [0.05...0.15) 中的所有数字返回,bin 宽度为 0.1。 1.0 会遭受同样的命运,0.9、0.8 等概率的一半

标签: python random numbers


【解决方案1】:

你可以使用

In [1]: weights.round(1)
Out[2]: array([0.4, 0.5, 0.2])

round 的参数是您想要的小数位数。它还接受否定参数,即四舍五入到大于 1 的 10 次方:

In [2]: np.array([123, 321, 332]).round(-1)
Out[2]: array([120, 320, 330])

【讨论】:

    【解决方案2】:

    仅用于可视化,您可以使用np.set_printoptions

    import numpy as np
    np.set_printoptions(precision=1, suppress=True)
    
    np.random.rand(4, 4)
    
    array([[0.8, 0.8, 0.3, 0.3],
           [0.1, 0.2, 0. , 0.2],
           [0.8, 0.2, 1. , 0.2],
           [0.2, 0.7, 0.6, 0.2]])
    

    【讨论】:

      【解决方案3】:

      你可以试试np.round:

      weights  = np.round(weights, 1)
      

      【讨论】:

        【解决方案4】:

        也许我的回答不是最有效的,但确实如此:

        for portfolio in range(2437):
            weights = np.random.random(3)
            weights /= np.sum(weights)
            t_weights = []
            for num in weights:
                num *= 10
                num = int(num)
                num = float(num) / 10
                t_weights.append(num)
            weights = t_weights
        
            print(weights)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多