简体   繁体   中英

How to generate random variables and sum all them in python

My problem explicitly is

Z=sum_(i)^12 (x_i).

where i is indices and x_i's are random number...

I need an explicit code in Python to produce 12 random variables and sum all them.

I tried write code using if, while loop, but I could not get it.

I need your help...

In probabilistic modelling, you can define distributions then sum them.

Personally, I use OpenTURNS platform for that.

import openturns as ot

x1 = ot.Normal(0, 2)  # Normal distribution mean = 0, std = 2
x2 = ot.Uniform(3, 5) # Uniform distribution between 3 and 5

sum = x1 + x2

That's it.

If x1,..., x12 are 12 distributions identically distributed you can write:

sum_12 = sum([x1] * 12)
import random
rand_sum = sum( random.random() for x in range(12) )

See the random documentation for more info.

In order to be able to use arbitrary variable just structure it as a function. You can structure it similar to l82Munch, but this may be more readable for you since your just starting. Note that range is a generator function that returns a list up to the last call. So range(1,3) returns [1,2]

import random
def rand_sum(i, j):    
    sum_list = []
    for rand_num in range(i, j+1):
        sum_list.append(random.random()) # Check random docs for a function that returns
    return sum(sum_list)                 # a different set of randoms if this isn't 
                                         # appropriate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM