Generate random integers between 0 and 9

前端 未结 19 1835
无人共我
无人共我 2020-11-22 15:37

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4

19条回答
  •  醉酒成梦
    2020-11-22 16:29

    OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined defined class.

    The following simulates 12 outcomes of the distribution.

    import openturns as ot
    points = [[i] for i in range(10)]
    distribution = ot.UserDefined(points) # By default, with equal weights.
    for i in range(12):
        x = distribution.getRealization()
        print(i,x)
    

    This prints:

    0 [8]
    1 [7]
    2 [4]
    3 [7]
    4 [3]
    5 [3]
    6 [2]
    7 [9]
    8 [0]
    9 [5]
    10 [9]
    11 [6]
    

    The brackets are there becausex is a Point in 1-dimension. It would be easier to generate the 12 outcomes in a single call to getSample:

    sample = distribution.getSample(12)
    

    would produce:

    >>> print(sample)
         [ v0 ]
     0 : [ 3  ]
     1 : [ 9  ]
     2 : [ 6  ]
     3 : [ 3  ]
     4 : [ 2  ]
     5 : [ 6  ]
     6 : [ 9  ]
     7 : [ 5  ]
     8 : [ 9  ]
     9 : [ 5  ]
    10 : [ 3  ]
    11 : [ 2  ]
    

    More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html

提交回复
热议问题