# Explain Linearity of Expectation using a program in Python

The linearity of expectation simply means that the expectation or probability of a sum of random variables is equal to the sum of expectation (or probability) of the individual random variables.

There are many algorithms written to prove this. Here we are going to prove the same by finding the sum of two unbiased dices.

## Understanding Random Variables

For those who are new to the topic, Random Variables is studied under Discrete Mathematics.

A Random variable is a set of possible outcomes of an experiment. They are called random because they can take any value from a set of possible values. There is no specific order like incremental or decremental, they are completely random.

For example: Tossing a coin can give you two outcomes

outcomes={ HEAD,TAIL}

any outcomes that may come from this experiment is a random variable.

## Proof from Python Code: Linearity of Expectation

We take two variables namely dice1 and dice2 and get random values on drawing these. The possible values on drawing a dice are `{1,2,3,4,5,6}`

The minimum sum that we could get is ->2 (1 on both)

The maximum sum we could get is ->12 (6 on both)

2==> (1,1) 3==> (2,1)(1,2) 4==> (2,2)(1,3)(3,1) 5==> (1,4)(4,1)(2,3)(3,2) 6==> (1,5)(5,1)(2,4)(4,2)(3,3) 7==> (1,6)(6,1)(5,2)(2,5)(4,3)(3,4) 8==> (4,4)(5,3)(3,5)(6,2)(2,6) 9==> (3,6)(6,3)(4,5)(5,4) 10==>(5,5)(6,4)(4,6) 11==>(5,6)(6,5) 12==>(6,6)

On finding the sum of every possibility we see that the expectation or probability of 7 is the highest.

import random possible_outcomes=[1,2,3,4,5,6] total=[] i=0 while(i!=1000): dice1=random.choice(possible_outcomes) dice2=random.choice(possible_outcomes) total.append(dice1+dice2) i+=1

Now after getting the random values for the dices and adding them up together, let’s see the results.

#module for graphic representation in python import matplotlib.pyplot as plt plt.hist(total,bins=30) # This python module will help us draw histograms to understand the data better. #OUTPUT (array([ 23., 0., 0., 53., 0., 0., 75., 0., 0., 101., 0., 0., 130., 0., 0., 176., 0., 0., 138., 0., 0., 117., 0., 0., 95., 0., 0., 68., 0., 24.]), array([ 2. , 2.33333333, 2.66666667, 3. , 3.33333333, 3.66666667, 4. , 4.33333333, 4.66666667, 5. , 5.33333333, 5.66666667, 6. , 6.33333333, 6.66666667, 7. , 7.33333333, 7.66666667, 8. , 8.33333333, 8.66666667, 9. , 9.33333333, 9.66666667, 10. , 10.33333333, 10.66666667, 11. , 11.33333333, 11.66666667, 12. ]), <a list of 30 Patch objects>)

A histogram of the output shows that the maximum number of times the 7 was observed. Hence showing Linearity of Expectation.

You can view the histogram from the link given below.

## Leave a Reply