# Exercise - Expected Value

## Introduction

In this notebook you will find exercises about the expected value. You will calculate it analytically and programatically using discrete values.

In order to detect errors in your own code, execute the notebook cells containing assert or assert_almost_equal. These statements raise exceptions, as long as the calculated result is not yet correct.

## Requirements

### Knowledge

To complete this exercise notebook you should possess knowledge about the following topics.

• Probability density function (pdf)
• Probability mass function (pmf)
• Expected value

The following literature can help you to acquire this knowledge:

### Python Modules

# External Modules
import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline

## Exercises

### Exercise - Probability Density Function

#### Pen & Paper Exercise

Given a probability density function$p(x)$. Its probability density between$0$ and$4$ is calculated with$p(x)=Cx$ and$p(x)=0$ otherwise.

Or formally:

$$p(x) = \begin{cases} Cx & \text{for } x \in [0, 4] \\ 0 & \text{for } x \notin [0, 4] \\ \end{cases}$$

Calculate the value of the constant$C$.

# Complete this cell

C = # Assign the right value you've calculated
# Executing this cell must not throw an Exception
# The solution is obfuscated so you can solve the exercise without unintendedly spoiling yourself

obfuscated_solution_1 = (23424+234-1024-23424+-2342-442+4422-444) / 3232
assert C == obfuscated_solution_1

### Exercise - Expected Value

Calculate the expected value of$\mathbb E [f(x)] \text{ with }f(x)=x^2$ with respect to the probability density$p$. Formally:

$s = \mathbb E_{x \sim p} [f(x)] \text{ with }f(x)=x^2$

1. Analytically (Pen & Paper Exercise)
2. Using numpy with discrete values for$x$: x = np.linspace(0,4, int(10e5))
# Complete this cell for Task #2

x = np.linspace(0,4, int(10e5))

# (...)

#uncomment the next line
#s = ?
### Plot visualizing p and f

plt.plot(x, x*obfuscated_solution_1, label='p(x)')
plt.plot(x, x**2, label='f(x)')
plt.ylim(0,16)
plt.xlabel('x')
plt.legend()

## Summary and Outlook

In this Notebook you used a basic property of probability density functions to compute an unknown constant. You computed the extepected value of a function with respect to a pdf analytically and you approximated it using discrete values.

In Exercise - Monte Carlo Estimator you will see, that an approximation using np.linspace(...) can sometimes be a very bad idea. Instead you will estimate the function using Monte Carlo estimator and inverse transform sampling (also known as Smirnov Transform) in order to draw samples using the correct distribution.

## Literature

### Notebook License (CC-BY-SA 4.0)

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

HTW Berlin - Angewandte Informatik - Advanced Topics - Exercise - Expected Value
by Christian Herta, Klaus Strohmenger