# Difference between revisions of "stat340s13"

If you use ideas, plots, text, code and other intellectual property developed by someone else in your wikicoursenote' contribution , you have to cite the original source. If you copy a sentence or a paragraph from work done by someone else, in addition to citing the original source you have to use quotation marks to identify the scope of the copied material. Evidence of copying or plagiarism will cause a failing mark in the course.

Example of citing the original source

Assumptions Underlying Principal Component Analysis can be found here<ref>http://support.sas.com/publishing/pubcat/chaps/55129.pdf</ref>

## Important Notes

To make distinction between the material covered in class and additional material that you have add to the course, use the following convention. For anything that is not covered in the lecture write:

In the news recently was a story that captures some of the ideas behind PCA. Over the past two years, Scott Golder and Michael Macy, researchers from Cornell University, collected 509 million Twitter messages from 2.4 million users in 84 different countries. The data they used were words collected at various times of day and they classified the data into two different categories: positive emotion words and negative emotion words. Then, they were able to study this new data to evaluate subjects' moods at different times of day, while the subjects were in different parts of the world. They found that the subjects generally exhibited positive emotions in the mornings and late evenings, and negative emotions mid-day. They were able to "project their data onto a smaller dimensional space" using PCS. Their paper, "Diurnal and Seasonal Mood Vary with Work, Sleep, and Daylength Across Diverse Cultures," is available in the journal Science.<ref>http://www.pcworld.com/article/240831/twitter_analysis_reveals_global_human_moodiness.html</ref>.

Assumptions Underlying Principal Component Analysis can be found here<ref>http://support.sas.com/publishing/pubcat/chaps/55129.pdf</ref>

## Introduction, Class 1 - Tuesday, May 7

### Course Instructor: Ali Ghodsi

Lecture:
001: T/Th 8:30-9:50am MC1085
002: T/Th 1:00-2:20pm DC1351
Tutorial:
2:30-3:20pm Mon M3 1006
Office Hours:
Friday at 10am, M3 4208

### Midterm

Monday June 17,2013 from 2:30pm-3:20pm

### Final

Saturday August 10,2013 from 7:30pm-10:00pm

### TA(s):

TA Day Time Location
Lu Cheng Monday 3:30-5:30 pm M3 3108, space 2
Han ShengSun Tuesday 4:00-6:00 pm M3 3108, space 2
Yizhou Fang Wednesday 1:00-3:00 pm M3 3108, space 1
Huan Cheng Thursday 3:00-5:00 pm M3 3111, space 1
Wu Lin Friday 11:00-1:00 pm M3 3108, space 1

### Four Fundamental Problems

1 Classification: Given input object X, we have a function which will take this input X and identify which 'class (Y)' it belongs to (Discrete Case)

  i.e taking value from x, we could predict y.


(For example, if you have 40 images of oranges and 60 images of apples (represented by x), you can estimate a function that takes the images and states what type of fruit it is - note Y is discrete in this case.)
2 Regression: Same as classification but in the continuous case except y is non discrete. Results from regression are often used for prediction,forecasting and etc. (Example of stock prices, height, weight, etc.)
(A simple practice might be investigating the hypothesis that higher levels of education cause higher levels of income.)
3 Clustering: Use common features of objects in same class or group to form clusters.(in this case, x is given, y is unknown; For example, clustering by provinces to measure average height of Canadian men.)
4 Dimensionality Reduction (also known as Feature extraction, Manifold learning): Used when we have a variable in high dimension space and we want to reduce the dimension

### Applications

Most useful when structure of the task is not well understood but can be characterized by a dataset with strong statistical regularity
Examples:

• Computer Vision, Computer Graphics, Finance (fraud detection), Machine Learning
• Search and recommendation (eg. Google, Amazon)
• Automatic speech recognition, speaker verification
• Text parsing
• Face identification
• Tracking objects in video
• Financial prediction(e.g. credit cards)
• Fraud detection
• Medical diagnosis

### Course Information

Prerequisite: (One of CS 116, 126/124, 134, 136, 138, 145, SYDE 221/322) and (STAT 230 with a grade of at least 60% or STAT 240) and (STAT 231 or 241)

Antirequisite: CM 361/STAT 341, CS 437, 457

General Information

• No required textbook
• Recommended: "Simulation" by Sheldon M. Ross
• Computing parts of the course will be done in Matlab, but prior knowledge of Matlab is not essential (will have a tutorial on it)
• First midterm will be held on Monday, June 17 from 2:30 to 3:30
• Announcements and assignments will be posted on Learn.
• Other course material on: http://wikicoursenote.com/wiki/
• Log on to both Learn and wikicoursenote frequently.
• Email all questions and concerns to UWStat340@gmail.com. Do not use your personal email address! Do not email instructor or TAs about the class directly to their personal accounts!

Wikicourse note (complete at least 12 contributions to get 10% of final mark): When applying for an account in the wikicourse note, please use the quest account as your login name while the uwaterloo email as the registered email. This is important as the quest id will be used to identify the students who make the contributions. Example:
User: questid
Email: questid@uwaterloo.ca
After the student has made the account request, do wait for several hours before students can login into the account using the passwords stated in the email. During the first login, students will be ask to create a new password for their account.

As a technical/editorial contributor: Make contributions within 1 week and do not copy the notes on the blackboard.

All contributions are now considered general contributions you must contribute to 50% of lectures for full marks

• A general contribution can be correctional (fixing mistakes) or technical (expanding content, adding examples, etc.) but at least half of your contributions should be technical for full marks.

Do not submit copyrighted work without permission, cite original sources. Each time you make a contribution, check mark the table. Marks are calculated on an honour system, although there will be random verifications. If you are caught claiming to contribute but have not, you will not be credited.

- you can submit your contributions multiple times.
- you will be able to edit the response right after submitting
- send email to make changes to an old response : uwstat340@gmail.com

### Tentative Topics

- Random variable and stochastic process generation
- Discrete-Event Systems
- Variance reduction
- Markov Chain Monte Carlo

## Class 2 - Thursday, May 9

### Generating Random Numbers

#### Introduction

Simulation is the imitation of a process or system over time. Computational power has introduced the possibility of using simulation study to analyze models used to describe a situation.

In order to perform a simulation study, we should: <br\> 1 Use a computer to generate (pseudo*) random numbers (rand in MATLAB).
2 Use these numbers to generate values of random variable from distributions: for example, set a variable in terms of uniform u ~ U(0,1).
3 Using the concept of discrete events, we show how the random variables can be used to generate the behavior of a stochastic model over time. (Note: A stochastic model is the opposite of deterministic model, where there are several directions the process can evolve to)
4 After continually generating the behavior of the system, we can obtain estimators and other quantities of interest.

The building block of a simulation study is the ability to generate a random number. This random number is a value from a random variable distributed uniformly on (0,1). There are many different methods of generating a random number:

Physical Method: Roulette wheel, lottery balls, dice rolling, card shuffling etc.
Numerically/Arithmetically: Use of a computer to successively generate pseudorandom numbers. The sequence of numbers can appear to be random; however they are deterministically calculated with an equation which defines pseudorandom.


(Source: Ross, Sheldon M., and Sheldon M. Ross. Simulation. San Diego: Academic, 1997. Print.)

• We use the prefix pseudo because computer generates random numbers based on algorithms, which suggests that generated numbers are not truly random. Therefore pseudo-random numbers is used.

In general, a deterministic model produces specific results given certain inputs by the model user, contrasting with a stochastic model which encapsulates randomness and probabilistic events.
A computer cannot generate truly random numbers because computers can only run algorithms, which are deterministic in nature. They can, however, generate Pseudo Random Numbers

Pseudo Random Numbers are the numbers that seem random but are actually determined by a relative set of original values. It is a chain of numbers pre-set by a formula or an algorithm, and the value jump from one to the next, making it look like a series of independent random events. The flaw of this method is that, eventually the chain returns to its initial position and pattern starts to repeat, but if we make the number set large enough we can prevent the numbers from repeating too early. Although the pseudo random numbers are deterministic, these numbers have a sequence of value and all of them have the appearances of being independent uniform random variables. Being deterministic, pseudo random numbers are valuable and beneficial due to the ease to generate and manipulate.

When people repeat the test many times, the results will be the closed express values, which make the trials look deterministic. However, for each trial, the result is random. So, it looks like pseudo random numbers.

#### Mod

Let $n \in \N$ and $m \in \N^+$, then by Division Algorithm, $\exists q, \, r \in \N \;\text{with}\; 0\leq r \lt m, \; \text{s.t.}\; n = mq+r$, where $q$ is called the quotient and $r$ the remainder. Hence we can define a binary function $\mod : \N \times \N^+ \rightarrow \N$ given by $r:=n \mod m$ which returns the remainder after division by m.
Generally, mod means taking the reminder after division by m.
We say that n is congruent to r mod m if n = mq + r, where m is an integer. Values are between 0 and m-1
if y = ax + b, then $b:=y \mod a$.

Example 1:

$30 = 4 \cdot 7 + 2$

$2 := 30\mod 7$

$25 = 8 \cdot 3 + 1$

$1: = 25\mod 3$

$-3=5\cdot (-1)+2$

$2:=-3\mod 5$

Example 2:

If $23 = 3 \cdot 6 + 5$

Then equivalently, $5 := 23\mod 6$

If $31 = 31 \cdot 1$

Then equivalently, $0 := 31\mod 31$

If $-37 = 40\cdot (-1)+ 3$

Then equivalently, $3 := -37\mod 40$

Example 3:
$77 = 3 \cdot 25 + 2$

$2 := 77\mod 3$

$25 = 25 \cdot 1 + 0$

$0: = 25\mod 25$

Note: $\mod$ here is different from the modulo congruence relation in $\Z_m$, which is an equivalence relation instead of a function.

The modulo operation is useful for determining if an integer divided by another integer produces a non-zero remainder. But both integers should satisfy $n = mq + r$, where $m$, $r$, $q$, and $n$ are all integers, and $r$ is smaller than $m$. The above rules also satisfy when any of $m$, $r$, $q$, and $n$ is negative integer, see the third example.

#### Mixed Congruential Algorithm

We define the Linear Congruential Method to be $x_{k+1}=(ax_k + b) \mod m$, where $x_k, a, b, m \in \N, \;\text{with}\; a, m \neq 0$. Given a seed (i.e. an initial value $x_0 \in \N$), we can obtain values for $x_1, \, x_2, \, \cdots, x_n$ inductively. The Multiplicative Congruential Method, invented by Berkeley professor D. H. Lehmer, may also refer to the special case where $b=0$ and the Mixed Congruential Method is case where $b \neq 0$
. Their title as "mixed" arises from the fact that it has both a multiplicative and additive term.

An interesting fact about Linear Congruential Method is that it is one of the oldest and best-known pseudo random number generator algorithms. It is very fast and requires minimal memory to retain state. However, this method should not be used for applications that require high randomness. They should not be used for Monte Carlo simulation and cryptographic applications. (Monte Carlo simulation will consider possibilities for every choice of consideration, and it shows the extreme possibilities. This method is not precise enough.)

"Source: STAT 340 Spring 2010 Course Notes"

First consider the following algorithm
$x_{k+1}=x_{k} \mod m$

such that: if $x_{0}=5(mod 150)$, $x_{n}=3x_{n-1}$, find $x_{1},x_{8},x_{9}$.
$x_{n}=(3^n)*5(mod 150)$
$x_{1}=45,x_{8}=105,x_{9}=15$

Example
$\text{Let }x_{0}=10,\,m=3$

\begin{align} x_{1} &{}= 10 &{}\mod{3} = 1 \\ x_{2} &{}= 1 &{}\mod{3} = 1 \\ x_{3} &{}= 1 &{}\mod{3} =1 \\ \end{align}

$\ldots$

Excluding $x_{0}$, this example generates a series of ones. In general, excluding $x_{0}$, the algorithm above will always generate a series of the same number less than M. Hence, it has a period of 1. The period can be described as the length of a sequence before it repeats. We want a large period with a sequence that is random looking. We can modify this algorithm to form the Multiplicative Congruential Algorithm.

$x_{k+1}=(a \cdot x_{k} + b) \mod m$(a little tip: $(a \cdot b)\mod c = (a\mod c)\cdot(b\mod c))$

Example
$\text{Let }a=2,\, b=1, \, m=3, \, x_{0} = 10$
\begin{align} \text{Step 1: } 0&{}=(2\cdot 10 + 1) &{}\mod 3 \\ \text{Step 2: } 1&{}=(2\cdot 0 + 1) &{}\mod 3 \\ \text{Step 3: } 0&{}=(2\cdot 1 + 1) &{}\mod 3 \\ \end{align}
$\ldots$

This example generates a sequence with a repeating cycle of two integers.

(If we choose the numbers properly, we could get a sequence of "random" numbers. How do we find the value of $a,b,$ and $m$? At the very least $m$ should be a very large, preferably prime number. The larger $m$ is, the higher the possibility to get a sequence of "random" numbers. This is easier to solve in Matlab. In Matlab, the command rand() generates random numbers which are uniformly distributed on the interval (0,1)). Matlab uses $a=7^5, b=0, m=2^{31}-1$ – recommended in a 1988 paper, "Random Number Generators: Good Ones Are Hard To Find" by Stephen K. Park and Keith W. Miller (Important part is that $m$ should be large and prime)

Note: $\frac {x_{n+1}}{m-1}$ is an approximation to the value of a U(0,1) random variable.

MatLab Instruction for Multiplicative Congruential Algorithm:
Before you start, you need to clear all existing defined variables and operations:

>>clear all
>>close all

>>a=17
>>b=3
>>m=31
>>x=5
>>mod(a*x+b,m)
ans=26
>>x=mod(a*x+b,m)


(Note:
1. Keep repeating this command over and over again and you will get random numbers – this is how the command rand works in a computer.
2. There is a function in MATLAB called RAND to generate a random number between 0 and 1.
For example, in MATLAB, we can use rand(1,1000) to generate 1000's numbers between 0 and 1. This is essentially a vector with 1 row, 1000 columns, with each entry a random number between 0 and 1.
3. If we would like to generate 1000 or more numbers, we could use a for loop

(Note on MATLAB commands:
1. clear all: clears all variables.
2. close all: closes all figures.
3. who: displays all defined variables.
4. clc: clears screen.
5. ; : prevents the results from printing.
6. disstool: displays a graphing tool.

>>a=13
>>b=0
>>m=31
>>x(1)=1
>>for ii=2:1000
x(ii)=mod(a*x(ii-1)+b,m);
end
>>size(x)
ans=1    1000
>>hist(x)


(Note: The semicolon after the x(ii)=mod(a*x(ii-1)+b,m) ensures that Matlab will not print the entire vector of x. It will instead calculate it internally and you will be able to work with it. Adding the semicolon to the end of this line reduces the run time significantly.)

This algorithm involves three integer parameters $a, b,$ and $m$ and an initial value, $x_0$ called the seed. A sequence of numbers is defined by $x_{k+1} = ax_k+ b \mod m$.

Note: For some bad $a$ and $b$, the histogram may not look uniformly distributed.

Note: In MATLAB, hist(x) will generate a graph representing the distribution. Use this function after you run the code to check the real sample distribution.

Example: $a=13, b=0, m=31$
The first 30 numbers in the sequence are a permutation of integers from 1 to 30, and then the sequence repeats itself so it is important to choose $m$ large to decrease the probability of each number repeating itself too early. Values are between $0$ and $m-1$. If the values are normalized by dividing by $m-1$, then the results are approximately numbers uniformly distributed in the interval [0,1]. There is only a finite number of values (30 possible values in this case). In MATLAB, you can use function "hist(x)" to see if it looks uniformly distributed. We saw that the values between 0-30 had the same frequency in the histogram, so we can conclude that they are uniformly distributed.

If $x_0=1$, then

$x_{k+1} = 13x_{k}\mod{31}$

So,

\begin{align} x_{0} &{}= 1 \\ x_{1} &{}= 13 \times 1 + 0 &{}\mod{31} = 13 \\ x_{2} &{}= 13 \times 13 + 0 &{}\mod{31} = 14 \\ x_{3} &{}= 13 \times 14 + 0 &{}\mod{31} =27 \\ \end{align}

etc.

For example, with $a = 3, b = 2, m = 4, x_0 = 1$, we have:

$x_{k+1} = (3x_{k} + 2)\mod{4}$

So,

\begin{align} x_{0} &{}= 1 \\ x_{1} &{}= 3 \times 1 + 2 \mod{4} = 1 \\ x_{2} &{}= 3 \times 1 + 2 \mod{4} = 1 \\ \end{align}

Another Example, a =3, b =2, m = 5, x_0=1 etc.

FAQ:

1.Why is it 1 to 30 instead of 0 to 30 in the example above?
$b = 0$ so in order to have $x_k$ equal to 0, $x_{k-1}$ must be 0 (since $a=13$ is relatively prime to 31). However, the seed is 1. Hence, we will never observe 0 in the sequence.
Alternatively, {0} and {1,2,...,30} are two orbits of the left multiplication by 13 in the group $\Z_{31}$.
2.Will the number 31 ever appear?Is there a probability that a number never appears?
The number 31 will never appear. When you perform the operation $\mod m$, the largest possible answer that you could receive is $m-1$. Whether or not a particular number in the range from 0 to $m - 1$ appears in the above algorithm will be dependent on the values chosen for $a, b$ and $m$.

Examples:[From Textbook]
$\text{If }x_0=3 \text{ and } x_n=(5x_{n-1}+7)\mod 200$, $\text{find }x_1,\cdots,x_{10}$.
Solution:
\begin{align} x_1 &{}= (5 \times 3+7) &{}\mod{200} &{}= 22 \\ x_2 &{}= 117 &{}\mod{200} &{}= 117 \\ x_3 &{}= 592 &{}\mod{200} &{}= 192 \\ x_4 &{}= 2967 &{}\mod{200} &{}= 167 \\ x_5 &{}= 14842 &{}\mod{200} &{}= 42 \\ x_6 &{}= 74217 &{}\mod{200} &{}= 17 \\ x_7 &{}= 371092 &{}\mod{200} &{}= 92 \\ x_8 &{}= 1855467 &{}\mod{200} &{}= 67 \\ x_9 &{}= 9277342 &{}\mod{200} &{}= 142 \\ x_{10} &{}= 46386717 &{}\mod{200} &{}= 117 \\ \end{align}

Matlab code: a=5; b=7; m=200; x(1)=3; for ii=2:1000 x(ii)=mod(a*x(ii-1)+b,m); end size(x); hist(x)

Typically, it is good to choose $m$ such that $m$ is large, and $m$ is prime. Careful selection of parameters '$a$' and '$b$' also helps generate relatively "random" output values, where it is harder to identify patterns. For example, when we used a composite (non prime) number such as 40 for $m$, our results were not satisfactory in producing an output resembling a uniform distribution.

The computed values are between 0 and $m-1$. If the values are normalized by dividing by $m-1$, their result is numbers uniformly distributed on the interval $\left[0,1\right]$ (similar to computing from uniform distribution).

From the example shown above, if we want to create a large group of random numbers, it is better to have large, prime $m$ so that the generated random values will not repeat after several iterations. Note: the period for this example is 8: from '$x_2$' to '$x_9$'.

There has been a research on how to choose uniform sequence. Many programs give you the options to choose the seed. Sometimes the seed is chosen by CPU.

Theorem (extra knowledge)
Let c be a non-zero constant. Then for any seed x0, and LCG will have largest max. period if and only if
(i) m and c are coprime;
(ii) (a-1) is divisible by all prime factor of m;
(iii) if and only if m is divisible by 4, then a-1 is also divisible by 4.

We want our LCG to have a large cycle. We call a cycle with m element the maximal period. We can make it bigger by making m big and prime. Recall:any number you can think of can be broken into a factor of prime Define coprime:Two numbers X and Y, are coprime if they do not share any prime factors.

Example:

Xn=(15Xn-1 + 4) mod 7


(i) m=7 c=4 -> coprime;
(ii) a-1=14 and a-1 is divisible by 7;
(iii) dose not apply.
(The extra knowledge stops here)

In this part, I learned how to use R code to figure out the relationship between two integers division, and their remainder. And when we use R to calculate R with random variables for a range such as(1:1000),the graph of distribution is like uniform distribution.

#### Summary of Multiplicative Congruential Algorithm

Problem: generate Pseudo Random Numbers.

Plan:

1. find integer: a b m(large prime) x0(the seed) .
2. $x_{k+1}=(ax_{k}+b)$mod m

Matlab Instruction:

>>clear all
>>close all
>>a=17
>>b=3
>>m=31
>>x=5
>>mod(a*x+b,m)
ans=26
>>x=mod(a*x+b,m)


Another algorithm for generating pseudo random numbers is the multiply with carry method. Its simplest form is similar to the linear congruential generator. They differs in that the parameter b changes in the MWC algorithm. It is as follows:

1.) xk+1 = axk + bk mod m
2.) bk+1 = floor((axk + bk)/m)
3.) set k to k + 1 and go to step 1 Source

### Inverse Transform Method

Now that we know how to generate random numbers, we use these values to sample form distributions such as exponential. However, to easily use this method, the probability distribution consumed must have a cumulative distribution function (cdf) $F$ with a tractable (that is, easily found) inverse $F^{-1}$.

Theorem:
If we want to generate the value of a discrete random variable X, we must generate a random number U, uniformly distributed over (0,1). Let $F:\R \rightarrow \left[0,1\right]$ be a cdf. If $U \sim U\left[0,1\right]$, then the random variable given by $X:=F^{-1}\left(U\right)$ follows the distribution function $F\left(\cdot\right)$, where $F^{-1}\left(u\right):=\inf F^{-1}\big(\left[u,+\infty\right)\big) = \inf\{x\in\R | F\left(x\right) \geq u\}$ is the generalized inverse.
Note: $F$ need not be invertible everywhere on the real line, but if it is, then the generalized inverse is the same as the inverse in the usual case. We only need it to be invertible on the range of F(x), [0,1].

Proof of the theorem:
The generalized inverse satisfies the following:

$P(X\leq x)$

$= P(F^{-1}(U)\leq x)$ (since $X= F^{-1}(U)$ by the inverse method)
$= P((F(F^{-1}(U))\leq F(x))$ (since $F$ is monotonically increasing)
$= P(U\leq F(x))$ (since $P(U\leq a)= a$ for $U \sim U(0,1), a \in [0,1]$,
$= F(x) , \text{ where } 0 \leq F(x) \leq 1$

This is the c.d.f. of X.

That is $F^{-1}\left(u\right) \leq x \Leftrightarrow u \leq F\left(x\right)$

Finally, $P(X \leq x) = P(F^{-1}(U) \leq x) = P(U \leq F(x)) = F(x)$, since $U$ is uniform on the unit interval.

This completes the proof.

Therefore, in order to generate a random variable X~F, it can generate U according to U(0,1) and then make the transformation x=$F^{-1}(U)$

Note that we can apply the inverse on both sides in the proof of the inverse transform only if the pdf of X is monotonic. A monotonic function is one that is either increasing for all x, or decreasing for all x. Of course, this holds true for all CDFs, since they are monotonic by definition.

In short, what the theorem tells us is that we can use a random number $U from U(0,1)$ to randomly sample a point on the CDF of X, then apply the inverse of the CDF to map the given probability to its domain, which gives us the random variable X.

Example 1 - Exponential: $f(x) = \lambda e^{-\lambda x}$
Calculate the CDF:
$F(x)= \int_0^x f(t) dt = \int_0^x \lambda e ^{-\lambda t}\ dt$ $= \frac{\lambda}{-\lambda}\, e^{-\lambda t}\, | \underset{0}{x}$ $= -e^{-\lambda x} + e^0 =1 - e^{- \lambda x}$
Solve the inverse:
$y=1-e^{- \lambda x} \Rightarrow 1-y=e^{- \lambda x} \Rightarrow x=-\frac {ln(1-y)}{\lambda}$
$y=-\frac {ln(1-x)}{\lambda} \Rightarrow F^{-1}(x)=-\frac {ln(1-x)}{\lambda}$
Note that 1 − U is also uniform on (0, 1) and thus −log(1 − U) has the same distribution as −logU.
Steps:
Step 1: Draw U ~U[0,1];
Step 2: $x=\frac{-ln(U)}{\lambda}$

EXAMPLE 2 Normal distribution G(y)=P[Y<=y)

     =P[-sqr (y) < z < sqr (y))
=integrate from -sqr(z) to Sqr(z) 1/sqr(2pi) e ^(-z^2/2) dz
= 2 integrate from 0 to sqr(y)  1/sqr(2pi) e ^(-z^2/2) dz


its the cdf of Y=z^2

pdf g(y)= G'(y) pdf pf x^2 (1)

MatLab Code:

>>u=rand(1,1000);
>>hist(u)       # this will generate a fairly uniform diagram


#let λ=2 in this example; however, you can make another value for λ
>>x=(-log(1-u))/2;
>>size(x)       #1000 in size
>>figure
>>hist(x)       #exponential


Example 2 - Continuous Distribution:

$f(x) = \dfrac {\lambda } {2}e^{-\lambda \left| x-\theta \right| } for -\infty \lt X \lt \infty , \lambda \gt 0$

Calculate the CDF:

$F(x)= \frac{1}{2} e^{-\lambda (\theta - x)} , for \ x \le \theta$
$F(x) = 1 - \frac{1}{2} e^{-\lambda (x - \theta)}, for \ x \gt \theta$

Solve for the inverse:

$F^{-1}(x)= \theta + ln(2y)/\lambda, for \ 0 \le y \le 0.5$
$F^{-1}(x)= \theta - ln(2(1-y))/\lambda, for \ 0.5 \lt y \le 1$

Algorithm:
Steps:
Step 1: Draw U ~ U[0, 1];
Step 2: Compute $X = F^-1(U)$ i.e. $X = \theta + \frac {1}{\lambda} ln(2U)$ for U < 0.5 else $X = \theta -\frac {1}{\lambda} ln(2(1-U))$

Example 3 - $F(x) = x^5$:
Given a CDF of X: $F(x) = x^5$, transform U~U[0,1].
Sol: Let $y=x^5$, solve for x: $x=y^\frac {1}{5}$. Therefore, $F^{-1} (x) = x^\frac {1}{5}$
Hence, to obtain a value of x from F(x), we first set 'u' as an uniform distribution, then obtain the inverse function of F(x), and set $x= u^\frac{1}{5}$

Algorithm:
Steps:
Step 1: Draw U ~ rand[0, 1];
Step 2: X=U^(1/5);

Example 4 - BETA(1,β):
Given u~U[0,1], generate x from BETA(1,β)
Solution: $F(x)= 1-(1-x)^\beta$, $u= 1-(1-x)^\beta$
Solve for x: $(1-x)^\beta = 1-u$, $1-x = (1-u)^\frac {1}{\beta}$, $x = 1-(1-u)^\frac {1}{\beta}$
let β=3, use Matlab to construct N=1000 observations from Beta(1,3)
MatLab Code:

>> u = rand(1,1000);
x = 1-(1-u)^(1/3);
>> hist(x,50)
>> mean(x)


Example 5 - Estimating $\pi$:
Let's use rand() and Monte Carlo Method to estimate $\pi$
N= total number of points
Nc = total number of points inside the circle
Prob[(x,y) lies in the circle=$\frac {Area(circle)}{Area(square)}$
If we take square of size 2, circle will have area =$\pi (\frac {2}{2})^2 =\pi$.
Thus $\pi= 4(\frac {N_c}{N})$

  For example, UNIF(a,b)
$y = F(x) = (x - a)/ (b - a)$
$x = (b - a ) * y + a$
$X = a + ( b - a) * U$
where U is UNIF(0,1)


Limitations:
1. This method is flawed since not all functions are invertible or monotonic: generalized inverse is hard to work on.
2. It may be impractical since some CDF's and/or integrals are not easy to compute such as Gaussian distribution.

We learned how to prove the transformation from cdf to inverse cdf,and use the uniform distribution to obtain a value of x from F(x). We can also use uniform distribution in inverse method to determine other distributions. The probability of getting a point for a circle over the triangle is a closed uniform distribution, each point in the circle and over the triangle is almost the same. Then, we can look at the graph to determine what kind of distribution the graph resembles.

#### Probability Distribution Function Tool in MATLAB

disttool         #shows different distributions


This command allows users to explore different types of distribution and see how the changes affect the parameters on the plot of either a CDF or PDF.

change the value of mu and sigma can change the graph skew side.

## Class 3 - Tuesday, May 14

### Recall the Inverse Transform Method

Let U~Unif(0,1),then the random variable X = F-1(u) has distribution F.
To sample X with CDF F(x),

$1) U~ \sim~ Unif [0,1]$ 2) X = F-1(u)

Note: CDF of a U(a,b) random variable is:

$F(x)= \begin{cases} 0 & \text{for }x \lt a \\[8pt] \frac{x-a}{b-a} & \text{for }a \le x \lt b \\[8pt] 1 & \text{for }x \ge b \end{cases}$

Thus, for $U$ ~ $U(0,1)$, we have $P(U\leq 1) = 1$ and $P(U\leq 1/2) = 1/2$.
More generally, we see that $P(U\leq a) = a$.
For this reason, we had $P(U\leq F(x)) = F(x)$.

Reminder:
This is only for uniform distribution $U~ \sim~ Unif [0,1]$
$P (U \le 1) = 1$
$P (U \le 0.5) = 0.5$
$P (U \le a) = a$

$P(U\leq a)=a$

Note that on a single point there is no mass probability (i.e. $u$ <= 0.5, is the same as $u$ < 0.5) More formally, this is saying that $P(X = x) = F(x)- \lim_{s \to x^-}F(x)$ , which equals zero for any continuous random variable

#### Limitations of the Inverse Transform Method

Though this method is very easy to use and apply, it does have a major disadvantage/limitation:

• We need to find the inverse cdf $F^{-1}(\cdot)$. In some cases the inverse function does not exist, or is difficult to find because it requires a closed form expression for F(x).

For example, it is too difficult to find the inverse cdf of the Gaussian distribution, so we must find another method to sample from the Gaussian distribution.

In conclusion, we need to find another way of sampling from more complicated distributions

### Discrete Case

The same technique can be used for discrete case. We want to generate a discrete random variable x, that has probability mass function:

\begin{align}P(X = x_i) &{}= p_i \end{align}
$x_0 \leq x_1 \leq x_2 \dots \leq x_n$
$\sum p_i = 1$

Algorithm for applying Inverse Transformation Method in Discrete Case (Procedure):
1. Define a probability mass function for $x_{i}$ where i = 1,....,k. Note: k could grow infinitely.
2. Generate a uniform random number U, $U~ \sim~ Unif [0,1]$
3. If $U\leq p_{o}$, deliver $X = x_{o}$
4. Else, if $U\leq p_{o} + p_{1}$, deliver $X = x_{1}$
5. Repeat the process again till we reached to $U\leq p_{o} + p_{1} + ......+ p_{k}$, deliver $X = x_{k}$

Note that after generating a random U, the value of X can be determined by finding the interval $[F(x_{j-1}),F(x_{j})]$ in which U lies.

In summary: Generate a discrete r.v.x that has pmf:

  P(X=xi)=Pi,    x0<x1<x2<...


1. Draw U~U(0,1);
2. If F(x(i-1))<U<F(xi), x=xi.

Example 3.0:
Generate a random variable from the following probability function:

 x -2 -1 0 1 2 f(x) 0.1 0.5 0.07 0.03 0.3

1. Gen U~U(0,1)
2. If U < 0.5 then output -1
else if U < 0.8 then output 2
else if U < 0.9 then output -2
else if U < 0.97 then output 0 else output 1

Example 3.1 (from class): (Coin Flipping Example)
We want to simulate a coin flip. We have U~U(0,1) and X = 0 or X = 1.

We can define the U function so that:

If $U\leq 0.5$, then X = 0

and if $0.5 \lt U\leq 1$, then X =1.

This allows the probability of Heads occurring to be 0.5 and is a good generator of a random coin flip.

$U~ \sim~ Unif [0,1]$

\begin{align} P(X = 0) &{}= 0.5\\ P(X = 1) &{}= 0.5\\ \end{align}

$x = \begin{cases} 0, & \text{if } U\leq 0.5 \\ 1, & \text{if } 0.5 \lt U \leq 1 \end{cases}$

• Code
>>for ii=1:1000
u=rand;
if u<0.5
x(ii)=0;
else
x(ii)=1;
end
end
>>hist(x)


Note: The role of semi-colon in Matlab: Matlab will not print out the results if the line ends in a semi-colon and vice versa.

Example 3.2 (From class):

Suppose we have the following discrete distribution:

\begin{align} P(X = 0) &{}= 0.3 \\ P(X = 1) &{}= 0.2 \\ P(X = 2) &{}= 0.5 \end{align}

The cumulative distribution function (cdf) for this distribution is then:

$F(x) = \begin{cases} 0, & \text{if } x \lt 0 \\ 0.3, & \text{if } x \lt 1 \\ 0.5, & \text{if } x \lt 2 \\ 1, & \text{if } x \ge 2 \end{cases}$

Then we can generate numbers from this distribution like this, given $U \sim~ Unif[0, 1]$:

$x = \begin{cases} 0, & \text{if } U\leq 0.3 \\ 1, & \text{if } 0.3 \lt U \leq 0.5 \\ 2, & \text{if } 0.5 \lt U\leq 1 \end{cases}$

"Procedure"
1. Draw U~u (0,1)
2. if U<=0.3 deliver x=0
3. else if 0.3<U<=0.5 deliver x=1
4. else 0.5<U<=1 deliver x=2

Can you find a faster way to run this algorithm? Consider:

$x = \begin{cases} 2, & \text{if } U\leq 0.5 \\ 1, & \text{if } 0.5 \lt U \leq 0.7 \\ 0, & \text{if } 0.7 \lt U\leq 1 \end{cases}$

The logic for this is that U is most likely to fall into the largest range. Thus by putting the largest range (in this case x >= 0.5) we can improve the run time of this algorithm. Could this algorithm be improved further using the same logic?

• Code (as shown in class)

Use Editor window to edit the code

>>close all
>>clear all
>>for ii=1:1000
u=rand;
if u<=0.3
x(ii)=0;
elseif u<=0.5
x(ii)=1;
else
x(ii)=2;
end
end
>>size(x)
>>hist(x)


The algorithm above generates a vector (1,1000) containing 0's ,1's and 2's in differing proportions. Due to the criteria for accepting 0, 1 or 2 into the vector we get proportions of 0,1 &2 that correspond to their respective probabilities. So plotting the histogram (frequency of 0,1&2) doesn't give us the pmf but a frequency histogram that shows the proportions of each, which looks identical to the pmf.

Example 3.3: Generating a random variable from pdf

$f_{x}(x) = \begin{cases} 2x, & \text{if } 0\leq x \leq 1 \\ 0, & \text{if } otherwise \end{cases}$
$F_{x}(x) = \begin{cases} 0, & \text{if } x \lt 0 \\ \int_{0}^{x}2sds = x^{2}, & \text{if } 0\leq x \leq 1 \\ 1, & \text{if } x \gt 1 \end{cases}$
\begin{align} U = x^{2}, X = F^{-1}x(U)= U^{\frac{1}{2}}\end{align}

Example 3.4: Generating a Bernoulli random variable

\begin{align} P(X = 1) = p, P(X = 0) = 1 - p\end{align}
$F(x) = \begin{cases} 1-p, & \text{if } x \lt 1 \\ 1, & \text{if } x \ge 1 \end{cases}$

1. Draw $U~ \sim~ Unif [0,1]$
2. $X = \begin{cases} 0, & \text{if } 0 \lt U \lt 1-p \\ 1, & \text{if } 1-p \le U \lt 1 \end{cases}$

Example 3.5: Generating Binomial(n,p) Random Variable
$use p\left( x=i+1\right) =\dfrac {n-i} {i+1}\dfrac {p} {1-p}p\left( x=i\right)$

Step 1: Generate a random number $U$.
Step 2: $c = \frac {p}{(1-p)}$, $i = 0$, $pr = (1-p)^n$, $F = pr$
Step 3: If U<F, set X = i and stop,
Step 4: $pr = \, {\frac {c(n-i)}{(i+1)}} {pr}, F = F +pr, i = i+1$
Step 5: Go to step 3

• Note: These steps can be found in Simulation 5th Ed. by Sheldon Ross.
• Note: Another method by seeing the Binomial as a sum of n independent Bernoulli random variables, U1, ..., Un. Then set X equal to the number of Ui that are less than or equal to p. To use this method, n random numbers are needed and n comparisons need to be done. On the other hand, the inverse transformation method is simpler because only one random variable needs to be generated and it makes 1 + np comparisons.

Step 1: Generate n uniform numbers U1 ... Un.
Step 2: X = $\sum U_i \lt = p$ where P is the probability of success.

Example 3.6: Generating a Poisson random variable

"Let X ~ Poi(u). Write an algorithm to generate X. The PDF of a poisson is:

\begin{align} f(x) = \frac {\, e^{-u} u^x}{x!} \end{align}

We know that

\begin{align} P_{x+1} = \frac {\, e^{-u} u^{x+1}}{(x+1)!} \end{align}

The ratio is \begin{align} \frac {P_{x+1}}{P_x} = ... = \frac {u}{{x+1}} \end{align} Therefore, \begin{align} P_{x+1} = \, {\frac {u}{x+1}} P_x\end{align}

Algorithm:
1) Generate U ~ U(0,1)
2) \begin{align} X = 0 \end{align}

  \begin{align} F = P(X = 0) = e^{-u}*u^0/{0!} = e^{-u} = p \end{align}


3) If U<F, output x

  Else, \begin{align} p = (u/(x+1))^p \end{align}
\begin{align} F = F + p \end{align}
\begin{align} x = x + 1 \end{align}


4) Go to 1"

Acknowledgements: This is an example from Stat 340 Winter 2013

Example 3.7: Generating Geometric Distribution:

Consider Geo(p) where p is the probability of success, and define random variable X such that X is the total number of trials required to achieve the first success. x=1,2,3..... We have pmf: $P(X=x_i) = \, p (1-p)^{x_{i}-1}$ We have CDF: $F(x)=P(X \leq x)=1-P(X\gt x) = 1-(1-p)^x$, P(X>x) means we get at least x failures before we observe the first success. Now consider the inverse transform:

$x = \begin{cases} 1, & \text{if } U\leq p \\ 2, & \text{if } p \lt U \leq 1-(1-p)^2 \\ 3, & \text{if } 1-(1-p)^2 \lt U\leq 1-(1-p)^3 \\ .... k, & \text{if } 1-(1-p)^{k-1} \lt U\leq 1-(1-p)^k .... \end{cases}$

Note: Unlike the continuous case, the discrete inverse-transform method can always be used for any discrete distribution (but it may not be the most efficient approach)

General Procedure
1. Draw U ~ U(0,1)
2. If $U \leq P_{0}$ deliver $x = x_{0}$
3. Else if $U \leq P_{0} + P_{1}$ deliver $x = x_{1}$
4. Else if $U \leq P_{0} + P_{1} + P_{2}$ deliver $x = x_{2}$
...

  Else if $U \leq P_{0} + ... + P_{k}$ deliver $x = x_{k}$


===Inverse Transform Algorithm for Generating a Binomial(n,p) Random Variable(from textbook)===
step 1: Generate a random number U
step 2: c=p/(1-p),i=0, pr=(1-p)n, F=pr.
step 3: If U<F, set X=i and stop.
step 4: pr =[c(n-i)/(i+1)]pr, F=F+pr, i=i+1.
step 5: Go to step 3.

Problems
Though this method is very easy to use and apply, it does have a major disadvantage/limitation: We need to find the inverse cdf F^{-1}(\cdot) . In some cases the inverse function does not exist, or is difficult to find because it requires a closed form expression for F(x). For example, it is too difficult to find the inverse cdf of the Gaussian distribution, so we must find another method to sample from the Gaussian distribution. In conclusion, we need to find another way of sampling from more complicated distributions Flipping a coin is a discrete case of uniform distribution, and the code below shows an example of flipping a coin 1000 times; the result is close to the expected value 0.5.
Example 2, as another discrete distribution, shows that we can sample from parts like 0,1 and 2, and the probability of each part or each trial is the same.
Example 3 uses inverse method to figure out the probability range of each random varible.

## Summary of Inverse Transform Method

Problem:generate types of distribution.

Plan:

Continuous case:

1. find CDF F
2. find the inverse F-1
3. Generate a list of uniformly distributed number {x}
4. {F-1(x)} is what we want

Matlab Instruction

>>u=rand(1,1000);
>>hist(u)
>>x=(-log(1-u))/2;
>>size(x)
>>figure
>>hist(x)


Discrete case:

1. generate a list of uniformly distributed number {u}
2. di=xi if$X=x_i,$ if $F(x_{i-1})\lt U\leq F(x_i)$
3. {di=xi} is what we want

Matlab Instruction

>>for ii=1:1000
u=rand;
if u<0.5
x(ii)=0;
else
x(ii)=1;
end
end
>>hist(x)


### Generalized Inverse-Transform Method

Valid for any CDF F(x): return X=min{x:F(x)$\leq$ U}, where U~U(0,1)

1. Continues, possibly with flat spots (i.e. not strictly increasing)

2. Discrete

3. Mixed continues discrete

Inverse transform method preserves monotonicity and correlation

which helps in

1. Variance reduction methods ...

2. Generating truncated distributions ...

3. Order statistics ...

### Acceptance-Rejection Method

Although the inverse transformation method does allow us to change our uniform distribution, it has two limits;

1. Not all functions have inverse functions (ie, the range of x and y have limit and do not fix the inverse functions)
2. For some distributions, such as Gaussian, it is too difficult to find the inverse

To generate random samples for these functions, we will use different methods, such as the Acceptance-Rejection Method. This method is more efficient than the inverse transform method. The basic idea is to find an alternative probability distribution with density function f(x);

Suppose we want to draw random sample from a target density function f(x), x∈Sx, where Sx is the support of f(x). If we can find some constant c(≥1) (In practice, we prefer c as close to 1 as possible) and a density function g(x) having the same support Sx so that f(x)≤cg(x), ∀x∈Sx, then we can apply the procedure for Acceptance-Rejection Method. Typically we choose a density function that we already know how to sample from for g(x).

The main logic behind the Acceptance-Rejection Method is that:
1. We want to generate sample points from an unknown distribution, say f(x).
2. We use $\,cg(x)$ to generate points so that we have more points than f(x) could ever generate for all x. (where c is a constant, and g(x) is a known distribution)
3. For each value of x, we accept and reject some points based on a probability, which will be discussed below.

Note: If the red line was only g(x) as opposed to $\,c g(x)$ (i.e. c=1), then $g(x) \geq f(x)$ for all values of x if and only if g and f are the same functions. This is because the sum of pdf of g(x)=1 and the sum of pdf of f(x)=1, hence, $g(x) \ngeqq f(x)$ \,∀x.

Also remember that $\,c g(x)$ always generates higher probability than what we need. Thus we need an approach of getting the proper probabilities.

c must be chosen so that $f(x)\leqslant c g(x)$ for all value of x. c can only equal 1 when f and g have the same distribution. Otherwise:
Either use a software package to test if $f(x)\leqslant c g(x)$ for an arbitrarily chosen c > 0, or:
1. Find first and second derivatives of f(x) and g(x).
2. Identify and classify all local and absolute maximums and minimums, using the First and Second Derivative Tests, as well as all inflection points.
3. Verify that $f(x)\leqslant c g(x)$ at all the local maximums as well as the absolute maximums.
4. Verify that $f(x)\leqslant c g(x)$ at the tail ends by calculating $\lim_{x \to +\infty} \frac{f(x)}{\, c g(x)}$ and $\lim_{x \to -\infty} \frac{f(x)}{\, c g(x)}$ and seeing that they are both < 1. Use of L'Hopital's Rule should make this easy, since both f and g are p.d.f's, resulting in both of them approaching 0.
5.Efficiency: the number of times N that steps 1 and 2 need to be called(also the number of iterations needed to successfully generate X) is a random variable and has a geometric distribution with success probability $p=P(U \leq f(Y)/(cg(Y)))$ , $P(N=n)=(1-p(n-1))p ,n \geq 1$.Thus on average the number of iterations required is given by $E(N)=\frac{1} p$

c should be close to the maximum of f(x)/g(x), not just some arbitrarily picked large number. Otherwise, the Acceptance-Rejection method will have more rejections (since our probability $f(x)\leqslant c g(x)$ will be close to zero). This will render our algorithm inefficient.

The expected number of iterations of the algorithm required with an X is c.
Note:
1. Value around x1 will be sampled more often under cg(x) than under f(x).There will be more samples than we actually need, if $\frac{f(y)}{\, c g(y)}$ is small, the acceptance-rejection technique will need to be done to these points to get the accurate amount.In the region above x1, we should accept less and reject more.
2. Value around x2: number of sample that are drawn and the number we need are much closer. So in the region above x2, we accept more. As a result, g(x) and f(x) are comparable.
3. The constant c is needed because we need to adjust the height of g(x) to ensure that it is above f(x). Besides that, it is best to keep the number of rejected varieties small for maximum efficiency.

Another way to understand why the the acceptance probability is $\frac{f(y)}{\, c g(y)}$, is by thinking of areas. From the graph above, we see that the target function in under the proposed function c g(y). Therefore, $\frac{f(y)}{\, c g(y)}$ is the proportion or the area under c g(y) that also contains f(y). Therefore we say we accept sample points for which u is less then $\frac{f(y)}{\, c g(y)}$ because then the sample points are guaranteed to fall under the area of c g(y) that contains f(y).

There are 2 cases that are possible:
-Sample of points is more than enough, $c g(x) \geq f(x)$
-Similar or the same amount of points, $c g(x) \geq f(x)$
There is 1 case that is not possible:
-Less than enough points, such that $g(x)$ is greater than $f$, $g(x) \geq f(x)$

Procedure

1. Draw Y~g(.)
2. Draw U~u(0,1) (Note: U and Y are independent)
3. If $u\leq \frac{f(y)}{cg(y)}$ (which is $P(accepted|y)$) then x=y, else return to Step 1

Note: Recall $P(U\leq a)=a$. Thus by comparing u and $\frac{f(y)}{\, c g(y)}$, we can get a probability of accepting y at these points. For instance, at some points that cg(x) is much larger than f(x), the probability of accepting x=y is quite small.
ie. At X1, low probability to accept the point since f(x) is much smaller than cg(x).
At X2, high probability to accept the point. $P(U\leq a)=a$ in Uniform Distribution.

Note: Since U is the variable for uniform distribution between 0 and 1. It equals to 1 for all. The condition depends on the constant c. so the condition changes to $c\leq \frac{f(y)}{g(y)}$

introduce the relationship of cg(x)and f(x),and prove why they have that relationship and where we can use this rule to reject some cases. and learn how to see the graph to find the accurate point to reject or accept the ragion above the random variable x. for the example, x1 is bad point and x2 is good point to estimate the rejection and acceptance

Some notes on the constant C
1. C is chosen such that $c g(y)\geq f(y)$, that is,$c g(y)$ will always dominate $f(y)$. Because of this, C will always be greater than or equal to one and will only equal to one if and only if the proposal distribution and the target distribution are the same. It is normally best to choose C such that the absolute maxima of both $c g(y)$ and $f(y)$ are the same.

2. $\frac {1}{C}$ is the area of $F(y)$ over the area of $c G(y)$ and is the acceptance rate of the points generated. For example, if $\frac {1}{C} = 0.7$ then on average, 70 percent of all points generated are accepted.

3. C is the average number of times Y is generated from g .

### Theorem

Let $f: \R \rightarrow [0,+\infty]$ be a well-defined pdf, and $\displaystyle Y$ be a random variable with pdf $g: \R \rightarrow [0,+\infty]$ such that $\exists c \in \R^+$ with $f \leq c \cdot g$. If $\displaystyle U \sim~ U(0,1)$ is independent of $\displaystyle Y$, then the random variable defined as $X := Y \vert U \leq \frac{f(Y)}{c \cdot g(Y)}$ has pdf $\displaystyle f$, and the condition $U \leq \frac{f(Y)}{c \cdot g(Y)}$ is denoted by "Accepted".

### Proof

Recall the conditional probability formulas:
\begin{align} P(A|B)=\frac{P(A \cap B)}{P(B)}, \text{ or }P(A|B)=\frac{P(B|A)P(A)}{P(B)} \text{ for pmf} \end{align}

$P(y|accepted)=f(y)=\frac{P(accepted|y)P(y)}{P(accepted)}$

based on the concept from procedure-step1:
$P(y)=g(y)$

$P(accepted|y)=\frac{f(y)}{cg(y)}$
(the larger the value is, the larger the chance it will be selected)

\begin{align} P(accepted)&=\int_y\ P(accepted|y)P(y)\\ &=\int_y\ \frac{f(s)}{cg(s)}g(s)ds\\ &=\frac{1}{c} \int_y\ f(s) ds\\ &=\frac{1}{c} \end{align}

Therefore:
\begin{align} P(x)&=P(y|accepted)\\ &=\frac{\frac{f(y)}{cg(y)}g(y)}{1/c}\\ &=\frac{\frac{f(y)}{c}}{1/c}\\ &=f(y)\end{align}

Here is an alternative introduction of Acceptance-Rejection Method

-Acceptance-Rejection Method is not good for all cases. The limitation with this method is that sometimes many points will be rejected. One obvious disadvantage is that it could be very hard to pick the $g(y)$ and the constant $c$ in some cases. We have to pick the SMALLEST C such that $cg(x) \leq f(x)$ else the the algorithm will not be efficient. This is because $f(x)/cg(x)$ will become smaller and probability $u \leq f(x)/cg(x)$ will go down and many points will be rejected making the algorithm inefficient.

-Note: When $f(y)$ is very different than $g(y)$, it is less likely that the point will be accepted as the ratio above would be very small and it will be difficult for $U$ to be less than this small value.
An example would be when the target function ($f$) has a spike or several spikes in its domain - this would force the known distribution ($g$) to have density at least as large as the spikes, making the value of $c$ larger than desired. As a result, the algorithm would be highly inefficient.

Acceptance-Rejection Method
Example 1 (discrete case)
We wish to generate X~Bi(2,0.5), assuming that we cannot generate this directly.
We use a discrete distribution DU[0,2] to approximate this.
$f(x)=Pr(X=x)=2Cx×(0.5)^2\,$

 $x$ 0 1 2 $f(x)$ 1/4 1/2 1/4 $g(x)$ 1/3 1/3 1/3 $c=f(x)/g(x)$ 3/4 3/2 3/4 $f(x)/(cg(x))$ 1/2 1 1/2

Since we need $c \geq f(x)/g(x)$
We need $c=3/2$

Therefore, the algorithm is:
1. Generate $u,v~U(0,1)$
2. Set $y= \lfloor 3*u \rfloor$ (This is using uniform distribution to generate DU[0,2]
3. If $(y=0)$ and $(v\lt \tfrac{1}{2}), output=0$
If $(y=2)$ and $(v\lt \tfrac{1}{2}), output=2$
Else if $y=1, output=1$

An elaboration of “c”
c is the expected number of times the code runs to output 1 random variable. Remember that when $u \lt \tfrac{f(x)}{cg(x)}$ is not satisfied, we need to go over the code again.

Proof

Let $f(x)$ be the function we wish to generate from, but we cannot use inverse transform method to generate directly.
Let $g(x)$ be the helper function
Let $kg(x)\gt =f(x)$
Since we need to generate y from $g(x)$,
$Pr(select y)=g(y)$
$Pr(output y|selected y)=Pr(u\lt f(y)/(cg(y)))= f(y)/(cg(y))$ (Since u~Unif(0,1))
$Pr(output y)=Pr(output y1|selected y1)Pr(select y1)+ Pr(output y2|selected y2)Pr(select y2)+…+ Pr(output yn|selected yn)Pr(select yn)=1/c$
Consider that we are asking for expected time for the first success, it is a geometric distribution with probability of success=1/c
Therefore, $E(X)=1/(1/c))=c$

Acknowledgements: Some materials have been borrowed from notes from Stat340 in Winter 2013.

Use the conditional probability to proof if the probability is accepted, then the result is closed pdf of the original one. the example shows how to choose the c for the two function $g(x)$ and $f(x)$.

### Example of Acceptance-Rejection Method

Generating a random variable having p.d.f.
$\displaystyle f(x) = 20x(1 - x)^3, 0\lt x \lt 1$
Since this random variable (which is beta with parameters (2,4)) is concentrated in the interval (0, 1), let us consider the acceptance-rejection method with
$\displaystyle g(x) = 1,0\lt x\lt 1$
To determine the constant c such that f(x)/g(x) <= c, we use calculus to determine the maximum value of
$\displaystyle f(x)/g(x) = 20x(1 - x)^3$
Differentiation of this quantity yields
$\displaystyle d/dx[f(x)/g(x)]=20*[(1-x)^3-3x(1-x)^2]$
Setting this equal to 0 shows that the maximal value is attained when x = 1/4, and thus,
$\displaystyle f(x)/g(x)\lt = 20*(1/4)*(3/4)^3=135/64=c$
Hence,
$\displaystyle f(x)/cg(x)=(256/27)*(x*(1-x)^3)$
and thus the simulation procedure is as follows:

1) Generate two random numbers U1 and U2 .

2) If U2<(256/27)*U1*(1-U1)3, set X=U1, and stop Otherwise return to step 1). The average number of times that step 1) will be performed is c = 135/64.

(The above example is from http://www.cs.bgu.ac.il/~mps042/acceptance.htm, example 2.)

use the derivative to proof the accepetance-rejection method, find the local maximum of f(x)/g(x). and we can calculate the best constant c.

### Another Example of Acceptance-Rejection Method

Generate a random variable from:
$\displaystyle f(x)=3*x^2, 0\lt x\lt 1$
Assume g(x) to be uniform over interval (0,1), where 0< x <1
Therefore:
$\displaystyle c = max(f(x)/(g(x)))= 3$

the best constant c is the max(f(x)/(cg(x))) and the c make the area above the f(x) and below the g(x) to be small. because g(.) is uniform so the g(x) is 1. max(g(x)) is 1
$\displaystyle f(x)/(cg(x))= x^2$
Acknowledgement: this is example 1 from http://www.cs.bgu.ac.il/~mps042/acceptance.htm

## Class 4 - Thursday, May 16

Goals

• When we want to find target distribution $f(x)$, we need to first find a proposal distribution $g(x)$ that is easy to sample from.
• Relationship between the proposal distribution and target distribution is: $c \cdot g(x) \geq f(x)$, where c is constant. This means that the area of f(x) is under the area of $c \cdot g(x)$.
• Chance of acceptance is less if the distance between $f(x)$ and $c \cdot g(x)$ is big, and vice-versa, we use $c$ to keep $\frac {f(x)}{c \cdot g(x)}$ below 1 (so $f(x) \leq c \cdot g(x)$). Therefore, we must find the constant $C$ to achieve this.
• In other words, $C$ is chosen to make sure $c \cdot g(x) \geq f(x)$. However, it will not make sense if $C$ is simply chosen to be arbitrarily large. We need to choose $C$ such that $c \cdot g(x)$ fits $f(x)$ as tightly as possible. This means that we must find the minimum c such that the area of f(x) is under the area of c*g(x).
• The constant c cannot be a negative number.

How to find C:

\begin{align} &c \cdot g(x) \geq f(x)\\ &c\geq \frac{f(x)}{g(x)} \\ &c= \max \left(\frac{f(x)}{g(x)}\right) \end{align}

If $f$ and $g$ are continuous, we can find the extremum by taking the derivative and solve for $x_0$ such that:
$0=\frac{d}{dx}\frac{f(x)}{g(x)}|_{x=x_0}$

Thus $c = \frac{f(x_0)}{g(x_0)}$

Note: This procedure is called the Acceptance-Rejection Method.

The Acceptance-Rejection method involves finding a distribution that we know how to sample from, g(x), and multiplying g(x) by a constant c so that $c \cdot g(x)$ is always greater than or equal to f(x). Mathematically, we want $c \cdot g(x) \geq f(x)$. And it means, c has to be greater or equal to $\frac{f(x)}{g(x)}$. So the smallest possible c that satisfies the condition is the maximum value of $\frac{f(x)}{g(x)}$
. But in case of c being too large, the chance of acceptance of generated values will be small, thereby losing efficiency of the algorithm. Therefore, it is best to get the smallest possible c such that $c g(x) \geq f(x)$.

Important points:

• For this method to be efficient, the constant c must be selected so that the rejection rate is low. (The efficiency for this method is $\left ( \frac{1}{c} \right )$)
• It is easy to show that the expected number of trials for an acceptance is $\frac{Total Number of Trials} {C}$.
• recall the acceptance rate is 1/c. (Not rejection rate)
Let $X$ be the number of trials for an acceptance, $X \sim~ Geo(\frac{1}{c})$
$\mathbb{E}[X] = \frac{1}{\frac{1}{c}} = c$
• The number of trials needed to generate a sample size of $N$ follows a negative binomial distribution. The expected number of trials needed is then $cN$.
• So far, the only distribution we know how to sample from is the UNIFORM distribution.

Procedure:

1. Choose $g(x)$ (simple density function that we know how to sample, i.e. Uniform so far)
The easiest case is $U~ \sim~ Unif [0,1]$. However, in other cases we need to generate UNIF(a,b). We may need to perform a linear transformation on the $U~ \sim~ Unif [0,1]$ variable.
2. Find a constant c such that :$c \cdot g(x) \geq f(x)$, otherwise return to step 1.

Recall the general procedure of Acceptance-Rejection Method

1. Let $Y \sim~ g(y)$
2. Let $U \sim~ Unif [0,1]$
3. If $U \leq \frac{f(Y)}{c \cdot g(Y)}$ then X=Y; else return to step 1 (This is not the way to find C. This is the general procedure.)

Example:

Generate a random variable from the pdf
$f(x) = \begin{cases} 2x, & \mbox{if }0 \leqslant x \leqslant 1 \\ 0, & \mbox{otherwise} \end{cases}$

We can note that this is a special case of Beta(2,1), where, $beta(a,b)=\frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}x^{(a-1)}(1-x)^{(b-1)}$

Where Γ (n) = (n - 1)! if n is positive integer

$Gamma(z)=\int _{0}^{\infty }t^{z-1}e^{-t}dt$

Aside: Beta function

In mathematics, the beta function, also called the Euler integral of the first kind, is a special function defined by $B(x,y)=\int_0^1 \! {t^{(x-1)}}{(1-t)^{(y-1)}}\,dt$

$beta(2,1)= \frac{\Gamma(3)}{(\Gamma(2)\Gamma(1))}x^1 (1-x)^0 = 2x$

$g=u(0,1)$
$y=g$
$f(x)\leq c\cdot g(x)$
$c\geq \frac{f(x)}{g(x)}$
$c = \max \frac{f(x)}{g(x)}$

$c = \max \frac{2x}{1}, 0 \leq x \leq 1$
Taking x = 1 gives the highest possible c, which is c=2
Note that c is a scalar greater than 1.
cg(x) is proposal dist, and f(x) is target dist.

Note: g follows uniform distribution, it only covers half of the graph which runs from 0 to 1 on y-axis. Thus we need to multiply by c to ensure that $c\cdot g$ can cover entire f(x) area. In this case, c=2, so that makes g run from 0 to 2 on y-axis which covers f(x).

Comment:
From the picture above, we could observe that the area under f(x)=2x is a half of the area under the pdf of UNIF(0,1). This is why in order to sample 1000 points of f(x), we need to sample approximately 2000 points in UNIF(0,1). And in general, if we want to sample n points from a distritubion with pdf f(x), we need to scan approximately $n\cdot c$ points from the proposal distribution (g(x)) in total.
Step

1. Draw y~U(0,1)
2. Draw u~U(0,1)
3. if $u \leq \frac{(2\cdot y)}{(2\cdot 1)}, u \leq y,$ then $x=y$
4. Else go to Step 1

Note: In the above example, we sample 2 numbers. If second number (u) is less than or equal to first number (y), then accept x=y, if not then start all over.

Matlab Code

>>close all
>>clear all
>>ii=1;             # ii:numbers that are accepted
>>jj=1;             # jj:numbers that are generated
>>while ii<1000
y=rand;
u=rand;
jj=jj+1;
if u<=y
x(ii)=y;
ii=ii+1;
end
end
>>hist(x)          # It is a histogram
>>jj
jj = 2024         # should be around 2000


*Note: The reason that a for loop is not used is that we need to continue the looping until we get 1000 successful samples. We will reject some samples during the process and therefore do not know the number of y we are going to generate.
*Note2: In this example, we used c=2, which means we accept half of the points we generate on average. Generally speaking, 1/c would be the probability of acceptance, and an indicator of the efficiency of your chosen proposal distribution and algorithm.
*Note3: We use while instead of for when looping because we do not know how many iterations are required to generate 1000 successful samples. We can view this as a negative binomial distribution so while the expected number of iterations required is n * c, it will likely deviate from this amount. We expect 2000 in this case.
*Note4: If c=1, we will accept all points, which is the ideal situation. However, this is essentially impossible because if c = 1 then our distributions f(x) and g(x) must be identical, so we will have to be satisfied with as close to 1 as possible.

Use Inverse Method for this Example

$F(x)=\int_0^x \! 2s\,ds={x^2}-0={x^2}$
$y=x^2$
$x=\sqrt y$
$F^{-1}\left (\, x \, \right) =\sqrt x$
• Procedure
1: Draw $U~ \sim~ Unif [0,1]$
2: $x=F^{-1}\left (\, u\, \right) =\sqrt u$

Matlab Code

>>u=rand(1,1000);
>>x=u.^0.5;
>>hist(x)


Matlab Tip: Periods, ".",meaning "element-wise", are used to describe the operation you want performed on each element of a vector. In the above example, to take the square root of every element in U, the notation U.^0.5 is used. However if you want to take the square root of the entire matrix U the period, "." would be excluded. i.e. Let matrix B=U^0.5, then $B^T*B=U$. For example if we have a two 1 X 3 matrices and we want to find out their product; using "." in the code will give us their product. However, if we don't use ".", it will just give us an error. For example, a =[1 2 3] b=[2 3 4] are vectors, a.*b=[2 6 12], but a*b does not work since the matrix dimensions must agree.

Example for A-R method:

Given $f(x)= \frac{3}{4} (1-x^2), -1 \leq x \leq 1$, use A-R method to generate random number

Let g=U(-1,1) and g(x)=1/2

let y ~ f, $cg(x)\geq f(x), c\frac{1}{2} \geq \frac{3}{4} (1-x^2) /1, c=max 2\cdot\frac{3}{4} (1-x^2) = 3/2$

The process:

1: Draw U1 ~ U(0,1)
2: Draw U2 ~ U(0,1)
3: let $y = U1*2 - 1$
4: if $U2 \leq \frac { \frac{3}{4} * (1-y^2)} { \frac{3}{4}} = {1-y^2}$, then x=y, note that (3/4(1-y^2)/(3/4) is getting from f(y) / (cg(y)) )

##### Example of Acceptance-Rejection Method

\begin{align} & f(x) = 3x^2, 0\lt x\lt 1 \\ \end{align}<br\>

\begin{align} & g(x)=1, 0\lt x\lt 1 \\ \end{align}<br\>

$c = \max \frac{f(x)}{g(x)} = \max \frac{3x^2}{1} = 3$
$\frac{f(x)}{c \cdot g(x)} = x^2$

1. Generate two uniform numbers in the unit interval $U_1, U_2 \sim~ U(0,1)$
2. If $U_2 \leqslant {U_1}^2$, accept \begin{align}U_1\end{align} as the random variable with pdf \begin{align}f\end{align}, if not return to Step 1

We can also use \begin{align}g(x)=2x\end{align} for a more efficient algorithm

$c = \max \frac{f(x)}{g(x)} = \max \frac {3x^2}{2x} = \frac {3x}{2}$. Use the inverse method to sample from \begin{align}g(x)\end{align} \begin{align}G(x)=x^2\end{align}. Generate \begin{align}U\end{align} from \begin{align}U(0,1)\end{align} and set \begin{align}x=sqrt(u)\end{align}

1. Generate two uniform numbers in the unit interval $U_1, U_2 \sim~ U(0,1)$
2. If $U_2 \leq \frac{3\sqrt{U_1}}{2}$, accept $U_1$ as the random variable with pdf $f$, if not return to Step 1

• Note :the function \begin{align}q(x) = c * g(x)\end{align} is called an envelop or majoring function.

To obtain a better proposing function \begin{align}g(x)\end{align}, we can first assume a new \begin{align}q(x)\end{align} and then solve for the normalizing constant by integrating.
In the previous example, we first assume \begin{align}q(x) = 3x\end{align}. To find the normalizing constant, we need to solve $k *\sum 3x = 1$ which gives us k = 2/3. So,\begin{align}g(x) = k*q(x) = 2x\end{align}.

Possible Limitations

-This method could be computationally inefficient depending on the rejection rate. We may have to sample many points before
we get the 1000 accepted points. In the example we did in class relating the $f(x)=2x$,
we had to sample around 2070 points before we finally accepted 1000 sample points.
-If the form of the proposal distribution, g, is very different from target distribution, f, then c is very large and the algorithm is not computationally efficient.

Acceptance - Rejection Method Application on Normal Distribution

$X \sim∼ N(\mu,\sigma^2), \text{ or } X = \sigma Z + \mu, Z \sim~ N(0,1)$
$\vert Z \vert$ has probability density function of

f(x) = (2/$\sqrt{2\pi}$) e-x2/2

g(x) = e-x

Take h(x) = f(x)/g(x) and solve for h'(x) = 0 to find x so that h(x) is maximum.

Hence x=1 maximizes h(x) => c = $\sqrt{2e/\pi}$

Thus f(y)/cg(y) = e-(y-1)2/2

learn how to use code to calculate the c between f(x) and g(x).

How to transform $U(0,1)$ to $U(a, b)$

1. Draw U from $U(0,1)$

2. Take $Y=(b-a)U+a$

3. Now Y follows $U(a,b)$

Example: Generate a random variable z from the Semicircular density $f(x)= \frac{2}{\pi R^2} \sqrt{R^2-x^2}, -R\leq x\leq R$.

-> Proposal distribution: UNIF(-R, R)

-> We know how to generate using $U \sim UNIF (0,1)$ Let $Y= 2RU-R=R(2U-1)$, therefore Y follows $U(-R,R)$

-> In order to maximize the function we must maximize the top and minimize the bottom.

Now, we need to find c: Since c=max[f(x)/g(x)], where
$f(x)= \frac{2}{\pi R^2} \sqrt{R^2-x^2}$, $g(x)=\frac{1}{2R}$, $-R\leq x\leq R$
Thus, we have to maximize R^2-x^2. => When x=0, it will be maximized. Therefore, c=4/pi. * Note: This also means that the probability of accepting a point is $\pi/4$.

We will accept the points with limit f(x)/[cg(x)]. Since $\frac{f(y)}{cg(y)}=\frac{\frac{2}{\pi R^{2}} \sqrt{R^{2}-y^{2}}}{\frac{4}{\pi} \frac{1}{2R}}=\frac{\frac{2}{\pi R^{2}} \sqrt{R^{2}-R^{2}(2U-1)^{2}}}{\frac{2}{\pi R}}$

• Note: Y= R(2U-1)

We can also get Y= R(2U-1) by using the formula y = a+(b-a)*u, to transform U~(0,1) to U~(a,b). Letting a=-R and b=R, and substituting it in the formula y = a+(b-a)*u, we get Y= R(2U-1).

Thus, $\frac{f(y)}{cg(y)}=\sqrt{1-(2U-1)^{2}}$ * this also means the probability we can accept points

The algorithm to generate random variable x is then:

1. Draw $\ U$ from $\ U(0,1)$

2. Draw $\ U_{1}$ from $\ U(0,1)$

3. If $U_{1} \leq \sqrt{1-(2U-1)^2}, set x = U_{1}$

  else return to step 1.


The condition is
$U_{1} \leq \sqrt{(1-(2U-1)^2)}$
$\ U_{1}^2 \leq 1 - (2U -1)^2$
$\ U_{1}^2 - 1 \leq -(2U - 1)^2$
$\ 1 - U_{1}^2 \geq (2U - 1)^2$

One more example about AR method
(In this example, we will see how to determine the value of c when c is a function with unknown parameters instead of a value) Let $f(x)=x×e^{-x}, x \gt 0$
Use $g(x)=a×e^{-a×x}$ to generate random variable

Solution: First of all, we need to find c
$cg(x)\gt =f(x)$
$c\gt =\frac{f(x)}{g(x)}$
$\frac{f(x)}{g(x)}=\frac{x}{a} * e^{-(1-a)x}$
take derivative with respect to x, and set it to 0 to get the maximum,
$\frac{1}{a} * e^{-(1-a)x} - \frac{x}{a} * e^{-(1-a)x} * (1-a) = 0$
$x=\frac {1}{1-a}$

$\frac {f(x)}{g(x)} = \frac {e^{-1}}{a*(1-a)}$
$\frac {f(0)}{g(0)} = 0$
$\frac {f(\infty)}{g(\infty)} = 0$

therefore, $c= \frac {e^{-1}}{a*(1-a)}$

In order to minimize c, we need to find the appropriate a
Take derivative with respect to a and set it to be zero,
We could get $a= \frac {1}{2}$
$c=\frac{4}{e}$
Procedure:
1. Generate u v ~unif(0,1)
2. Generate y from g, since g is exponential with rate 2, let y=-0.5*ln(u)
3. If $v\lt \frac{f(y)}{c\cdot g(y)}$, output y
Else, go to 1

Acknowledgements: The example above is from Stat 340 Winter 2013 notes.

Summary of how to find the value of c
Let $h(x) = \frac {f(x)}{g(x)}$, and then we have the following:
1. First, take derivative of h(x) with respect to x, get x1;
2. Plug x1 into h(x) and get the value(or a function) of c, denote as c1;
3. Check the endpoints of x and sub the endpoints into h(x);
4. (if c1 is a value, then we can ignore this step) Since we want the smallest value of c such that $f(x) \leq c\cdot g(x)$ for all x, we want the unknown parameter that minimizes c.
So we take derivative of c1 with respect to the unknown parameter (ie k=unknown parameter) to get the value of k.
Then we submit k to get the value of c1. (Double check that $c_1 \geq 1$
5. Pick the maximum value of h(x) to be the value of c.

For the two examples above, we need to generate the probability function to uniform distribution, and figure out $c=max\frac {f(y)}{g(y)}$. If $v\lt \frac {f(y)}{c\cdot g(y)}$, output y.

Summary of when to use the Accept Rejection Method
1) When the calculation of inverse cdf cannot to be computed or is too difficult to compute.
2) When f(x) can be evaluated to at least one of the normalizing constant.
3) A constant c where $f(x)\leq c\cdot g(x)$
4) A uniform draw

#### Interpretation of 'C'

We can use the value of c to calculate the acceptance rate by $\tfrac{1}{c}$.

For instance, assume c=1.5, then we can tell that 66.7% of the points will be accepted ($\tfrac{1}{1.5} = 0.667$). We can also call the efficiency of the method is 66.7%.

Likewise, if the minimum value of possible values for C is $\tfrac{4}{3}$, $1/ \tfrac{4}{3}$ of the generated random variables will be accepted. Thus the efficient of the algorithm is 75%.

In order to ensure the algorithm is as efficient as possible, the 'C' value should be as close to one as possible, such that $\tfrac{1}{c}$ approaches 1 => 100% acceptance rate.

>> close All >> clear All >> i=1 >> j=0; >> while ii<1000 y=rand u=rand if u<=y; x(ii)=y ii=ii+1 end end

## Class 5 - Tuesday, May 21

Recall the example in the last lecture. The following code will generate a random variable required by the question.

• Code
>>close all
>>clear all
>>ii=1;
>>R=1;         #Note: that R is a constant in which we can change
i.e. if we changed R=4 then we would have a density between -4 and 4
>>while ii<1000
u1 = rand;
u2 = rand;
y = R*(2*u2-1);
if (1-u1^2)>=(2*u2-1)^2
x(ii) = y;
ii = ii + 1;       #Note: for beginner programmers that this step increases
the ii value for next time through the while loop
end
end
>>hist(x,20)                  # 20 is the number of bars

>>hist(x,30)                 #30 is the number of bars


calculate process: $u_{1} \lt = \sqrt (1-(2u-1)^2)$
$(u_{1})^2 \lt =(1-(2u-1)^2)$
$(u_{1})^2 -1 \lt =(-(2u-1)^2)$
$1-(u_{1})^2 \gt =((2u-1)^2-1)$

MATLAB tips: hist(x,y) plots a histogram of variable x, where y is the number of bars in the graph.

### Discrete Examples

• Example 1

Generate random variable $X$ according to p.m.f
\begin{align} P(x &=1) &&=0.15 \\ P(x &=2) &&=0.25 \\ P(x &=3) &&=0.3 \\ P(x &=4) &&=0.1 \\ P(x &=5) &&=0.2 \\ \end{align}

The discrete case is analogous to the continuous case. Suppose we want to generate an X that is a discrete random variable with pmf f(x)=P(X=x). Suppose also that we use the discrete uniform distribution as our target distribution, then $g(x)= P(X=x) =0.2$ for all X.

The following algorithm then yields our X:

Step 1 Draw discrete uniform distribution of 1, 2, 3, 4 and 5, $Y \sim~ g$.
Step 2 Draw $U \sim~ U(0,1)$.
Step 3 If $U \leq \frac{f(Y)}{c \cdot g(Y)}$, then X = Y ;

C can be found by maximizing the ratio :$\frac{f(x)}{g(x)}$. To do this, we want to maximize $f(x)$ and minimize $g(x)$.

$c = max \frac{f(x)}{g(x)} = \frac {0.3}{0.2} = 1.5$

Note: In this case $f(x)=P(X=x)=0.3$ (highest probability from the discrete probabilities in the question)

$\frac{p(x)}{cg(x)} = \frac{p(x)}{1.5*0.2} = \frac{p(x)}{0.3}$

Note: The U is independent from y in Step 2 and 3 above. ~The constant c is a indicator of rejection rate or efficiency of the algorithm. It can represent the average number of trials of the algorithm. Thus, a higher c would mean that the algorithm is comparatively inefficient.

the acceptance-rejection method of pmf, the uniform probability is the same for all variables, and there are 5 parameters(1,2,3,4,5), so g(x) is 0.2

Remember that we always want to choose $cg$ to be equal to or greater than $f$, but as close as possible.
limitations: If the form of the proposal dist g is very different from target dist f, then c is very large and the algorithm is not computatively efficient.

• Code for example 1
>>close all
>>clear all
>>p=[.15 .25 .3 .1 .2];    %This a vector holding the values
>>ii=1;
>>while ii < 1000
y=unidrnd(5);          %generates random numbers for the discrete uniform
u=rand;                 distribution with maximum 5.
if u<= p(y)/0.3
x(ii)=y;
ii=ii+1;
end
end
>>hist(x)


unidrnd(k) draws from the discrete uniform distribution of integers $1,2,3,...,k$ If this function is not built in to your MATLAB then we can do simple transformation on the rand(k) function to make it work like the unidrnd(k) function.

The acceptance rate is $\frac {1}{c}$, so the lower the c, the more efficient the algorithm. Theoretically, c equals 1 is the best case because all samples would be accepted; however it would only be true when the proposal and target distributions are exactly the same, which would never happen in practice.

For example, if c = 1.5, the acceptance rate would be $\frac {1}{1.5}=\frac {2}{3}$. Thus, in order to generate 1000 random values, on average, a total of 1500 iterations would be required.

A histogram to show 1000 random values of f(x), more random value make the probability close to the express probability value.

• Example 2

p(x=1)=0.1
p(x=2)=0.3
p(x=3)=0.6
Let g be the uniform distribution of 1, 2, or 3
g(x)= 1/3
$c=max(\tfrac{p_{x}}{g(x)})=0.6/(\tfrac{1}{3})=1.8$
Hence $\tfrac{p(x)}{cg(x)} = p(x)/(1.8 (\tfrac{1}{3}))= \tfrac{p(x)}{0.6}$

1,y~g
2,u~U(0,1)
3, If $U \leq \frac{f(y)}{cg(y)}$, set x = y. Else go to 1.

• Code for example 2
>>close all
>>clear all
>>p=[.1 .3 .6];     %This a vector holding the values
>>ii=1;
>>while ii < 1000
y=unidrnd(3);   %generates random numbers for the discrete uniform distribution with maximum 3
u=rand;
if u<= p(y)/0.6
x(ii)=y;
ii=ii+1;     %else ii=ii+1
end
end
>>hist(x)


• Example 3

Suppose \begin{align}p_{x} = e^{-3}3^{x}/x! , x\geq 0\end{align} (Poisson distribution)

First: Try the first few \begin{align}p_{x}'s\end{align}: 0.0498, 0.149, 0.224, 0.224, 0.168, 0.101, 0.0504, 0.0216, 0.0081, 0.0027 for \begin{align} x = 0,1,2,3,4,5,6,7,8,9 \end{align}

Proposed distribution: Use the geometric distribution for \begin{align}g(x)\end{align};

\begin{align}g(x)=p(1-p)^{x}\end{align}, choose \begin{align}p=0.25\end{align}

Look at \begin{align}p_{x}/g(x)\end{align} for the first few numbers: 0.199 0.797 1.59 2.12 2.12 1.70 1.13 0.647 0.324 0.144 for \begin{align} x = 0,1,2,3,4,5,6,7,8,9 \end{align}

We want \begin{align}c=max(p_{x}/g(x))\end{align} which is approximately 2.12

The general procedures to generate \begin{align}p(x)\end{align} is as follows:

1. Generate \begin{align}U_{1} \sim~ U(0,1); U_{2} \sim~ U(0,1)\end{align}

2. \begin{align}j = \lfloor \frac{ln(U_{1})}{ln(.75)} \rfloor+1;\end{align}

3. if $U_{2} \lt \frac{p_{j}}{cg(j)}$, set \begin{align}X = x_{j}\end{align}, else go to step 1.

Note: In this case, \begin{align}f(x)/g(x)\end{align} is extremely difficult to differentiate so we were required to test points. If the function is very easy to differentiate, we can calculate the max as if it were a continuous function then check the two surrounding points for which is the highest discrete value.

• Example 4 (Hypergeometric & Binomial)

Suppose we are given f(x) such that it is hypergeometically distributed, given 10 white balls, 5 red balls, and select 3 balls, let X be the number of red ball selected, without replacement.

Choose g(x) such that it is binomial distribution, Bin(3, 1/3). Find the rejection constant, c

Solution: For hypergeometric: $P(X=0) =\binom{10}{3}/\binom{15}{3} =0.2637, P(x=1)=\binom{10}{2} * \binom{5}{1} /\binom{15}{3}=0.4945, P(X=2)=\binom{10}{1} * \binom{5}{2} /\binom{15}{3}=0.2198,$

$P(X=3)=\binom{5}{3}/\binom{15}{3}= 0.02198$

For Binomial g(x): P(X=0) = (2/3)^3=0.2963; P(X=1)= 3*(1/3)*(2/3)^2 = 0.4444, P(X=2)=3*(1/3)^2*(2/3)=0.2222, P(X=3)=(1/3)^3=0.03704

Find the value of f/g for each X

X=0: 0.8898; X=1: 1.1127; X=2: 0.9891; X=3: 0.5934

Choose the maximum which is c=1.1127

Looking for the max f(x) is 0.4945 and the max g(x) is 0.4444, so we can calculate the max c is 1.1127. But for the graph, this c is not the best because it does not cover all the point of f(x), so we need to move the c*g(x) graph to cover all f(x), and decreasing the rejection ratio.

Limitation: If the shape of the proposed distribution g is very different from the target distribution f, then the rejection rate will be high (High c value). Computationally, the algorithm is always right; however it is inefficient and requires many iterations.
Here is an example:

In the above example, we need to move c*g(x) to the peak of f to cover the whole f. Thus c will be very large and 1/c will be small. The higher the rejection rate, more points will be rejected.
More on rejection/acceptance rate: 1/c is the acceptance rate. As c decreases (note: the minimum value of c is 1), the acceptance rate increases. In our last example, 1/c=1/1.5≈66.67%. Around 67% of points generated will be accepted.

the example below provides a better understanding about the pros and cons of the AR method. The AR method is useless when dealing with sampling distribution with a higher peak since c will be large, hence making our algorithm inefficient
which brings the acceptance rate low which leads to very time consuming sampling

## Acceptance-Rejection Method

Problem: The CDF is not invertible or it is difficult to find the inverse.

Plan:

1. Draw y~g(.)
2. Draw u~Unif(0,1)
3. If $u\leq \frac{f(y)}{cg(y)}$then set x=y. Else return to Step 1

x will have the desired distribution.

Matlab Example

close all
clear all
ii=1;
R=1;
while ii<1000
u1 = rand;
u2 = rand;
y = R*(2*u2-1);
if (1-u1^2)>=(2*u2-1)^2
x(ii) = y;
ii = ii + 1;
end
end
hist(x,20)


Recall that, Suppose we have an efficient method for simulating a random variable having probability mass function {q(j),j>=0}. We can use this as the basis for simulating from the distribution having mass function {p(j),j>=0} by first simulating a random variable Y having mass function {q(j)} and then accepting this simulated value with a probability proportional to p(Y)/q(Y).

Specifically, let c be a constant such that
p(j)/q(j)<=c for all j such that p(j)>0


We now have the following technique, called the acceptance-rejection method, for simulating a random variable X having mass function p(j)=P{X=j}.

### Sampling from commonly used distributions

Please note that this is not a general technique as is that of acceptance-rejection sampling. Later, we will generalize the distributions for multidimensional purposes.

• Gamma

The CDF of the Gamma distribution $Gamma(t,\lambda)$ is(t denotes the shape, $\lambda$ denotes the scale:
$F(x) = \int_0^{x} \frac{e^{-y}y^{t-1}}{(t-1)!} \mathrm{d}y, \; \forall x \in (0,+\infty)$, where $t \in \N^+ \text{ and } \lambda \in (0,+\infty)$.

Note that the CDF of the Gamma distribution does not have a closed form.

The gamma distribution is often used to model waiting times between a certain number of events. It can also be expressed as the sum of infinitely many independent and identically distributed exponential distributions. This distribution has two parameters: the number of exponential terms n, and the rate parameter $\lambda$. In this distribution there is the Gamma function, $\Gamma$ which has some very useful properties. "Source: STAT 340 Spring 2010 Course Notes"

Neither Inverse Transformation nor Acceptance-Rejection Method can be easily applied to Gamma distribution. However, we can use additive property of Gamma distribution to generate random variables.

If $X_1, \dots, X_t$ are independent exponential distributions with hazard rate $\lambda$ (in other words, $X_i\sim~ Exp (\lambda)$$, Exp (\lambda)= Gamma (1, \lambda)), then \Sigma_{i=1}^t X_i \sim~ Gamma (t, \lambda)$

Side notes: if $X_i\sim~ Gamma(a,\lambda)$ and $Y_i\sim~ Gamma(B,\lambda)$ are independent gamma distributions, then $\frac{X}{X+Y}$ has a distribution of $Beta(a,B).$

If we want to sample from the Gamma distribution, we can consider sampling from $t$ independent exponential distributions using the Inverse Method for each $X_i$ and add them up. Note that this only works the specific set of gamma distributions where t is a positive integer.

According to this property, a random variable that follows Gamma distribution is the sum of i.i.d (independent and identically distributed) exponential random variables. Now we want to generate 1000 values of $Gamma(20,10)$ random variables, so we need to obtain the value of each one by adding 20 values of $X_i \sim~ Exp(10)$. To achieve this, we generate a 20-by-1000 matrix whose entries follow $Exp(10)$ and add the rows together.
$x_1 \sim~Exp(\lambda)$
$x_2 \sim~Exp(\lambda)$
...
$x_t \sim~Exp(\lambda)$
$x_1+x_2+...+x_t~$

>>l=1
>>u-rand(1,1000);
>>x=-(1/l)*log(u);
>>hist(x)
>>rand


• Procedure
1. Sample independently from a uniform distribution $t$ times, giving $U_1,\dots,U_t \sim~ U(0,1)$
2. Use the Inverse Transform Method, $X_i = -\frac {1}{\lambda}\log(1-U_i)$, giving $X_1,\dots,X_t \sim~Exp(\lambda)$
3. Use the additive property,$X = \Sigma_{i=1}^t X_i \sim~ Gamma (t, \lambda)$

• Note for Procedure
1. If $U\sim~U(0,1)$, then $U$ and $1-U$ will have the same distribution (both follows $U(0,1)$)
2. This is because the range for $1-U$ is still $(0,1)$, and their densities are identical over this range.
3. Let $Y=1-U$, $Pr(Y\lt =y)=Pr(1-U\lt =y)=Pr(U\gt =1-y)=1-Pr(U\lt =1-y)=1-(1-y)=y$, thus $1-U\sim~U(0,1)$

• Code
>>close all
>>clear all
>>lambda = 1;
>>u = rand(20, 1000);            Note: this command generate a 20x1000 matrix
(which means we generate 1000 number for each X_i with t=20);
all the elements are generated by rand
>>x = (-1/lambda)*log(1-u);      Note: log(1-u) is essentially the same as log(u) only if u~U(0,1)
>>xx = sum(x)                    Note: sum(x) will sum all elements in the same column.
>>size(sum(x))                   Note: see the size of x if we forget it
>>hist(x(1:))                    Note: the graph of the first exponential distribution
>>hist(xx)


size(x) and size(u) are both 20*1000 matrix. Since if u~unif(0, 1), u and 1 - u have the same distribution, we can substitute 1-u with u to simply the equation. Alternatively, the following command will do the same thing with the previous commands.

• Code
>>close all
>>clear all
>>lambda = 1;
>>xx = sum((-1/lambda)*log(rand(20, 1000))); ''This is simple way to put the code in one line.
Here we can use either log(u) or log(1-u) since U~U(0,1);
>>hist(xx)


In the matrix rand(20,1000) means 20 row with 1000 numbers for each. use the code to show the generalize the distributions for multidimensional purposes in different cases, such as sum xi (each xi not equal xj), and they are independent, or matrix. Finally, we can see the conclusion is shown by the histogram.

### Other Sampling Method: Box Muller

• From cartesian to polar coordinates

$R=\sqrt{x_{1}^2+x_{2}^2}= x_{2}/sin(\theta)= x_{1}/cos(\theta)$
$tan(\theta)=x_{2}/x_{1} \rightarrow \theta=tan^{-1}(x_{2}/x_{1})$

• Box-Muller Transformation:

It is a transformation that consumes two continuous uniform random variables $X \sim U(0,1), Y \sim U(0,1)$ and outputs a bivariate normal random variable with $Z_1\sim N(0,1), Z_2\sim N(0,1).$

### Matlab

If X is a matrix,

• X(1,:) returns the first row
• X(:,1) returns the first column
• X(i,j) returns the (i,j)th entry
• sum(X,1) or sum(X) is a summation of the rows of X. The output is a row vector of the sums of each column.
• sum(X,2) is a summation of the columns of X, returning a vector.
• rand(r,c) will generate uniformly distributed random numbers in r rows and c columns.
• The dot operator (.), when placed before a function, such as +,-,^, *, and many others specifies to apply that function to every element of a vector or a matrix. For example, to add a constant c to elements of a matrix A, do A.+c as opposed to simply A+c. The dot operator is not required for functions that can only take a number as their input (such as log).
• Matlab processes loops very slow, while it is fast with matrices and vectors, so it is preferable to use the dot operator to and matrices of random numbers than loops if it is possible.

## Class 6 - Thursday, May 23

### Announcement

1. On the day of each lecture, students from the morning section can only contribute the first half of the lecture (i.e. 8:30 - 9:10 am), so that the second half can be saved for the ones from the afternoon section. After the day of lecture, students are free to contribute anything.

### Standard Normal distribution

If X ~ N(0,1) i.e. Standard Normal Distribution - then its p.d.f. is of the form

$f(x) = \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} x^2}$
• Warning : the General Normal distribution is:
 $f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} }$ which is almost useless in this course

where $\mu$ is the mean or expectation of the distribution and $\sigma$ is standard deviation

• N(0,1) is standard normal. $\mu$ =0 and $\sigma$=1

Let X and Y be independent standard normal.

Let $\theta$ and R denote the Polar coordinate of the vector (X, Y) where $X = R \cdot \sin\theta$ and $Y = R \cdot \cos \theta$

Note: R must satisfy two properties:

1. Be a positive number (as it is a length)
2. It must be from a distribution that has more data points closer to the origin so that as we go further from the origin, less points are generated (the two options are Chi-squared and Exponential distribution)

The form of the joint distribution of R and $\theta$ will show that the best choice for distribution of R2 is exponential.

We cannot use the Inverse Transformation Method since F(x) does not have a closed form solution. So we will use joint probability function of two independent standard normal random variables and polar coordinates to simulate the distribution:

We know that

$R^{2}= X^{2}+Y^{2}$ and $\tan(\theta) = \frac{y}{x}$ where X and Y are two independent standard normal

$f(x) = \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} x^2}$
$f(y) = \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} y^2}$
$f(x,y) = \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} x^2} * \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} y^2}=\frac{1}{2\pi}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} (x^2+y^2)}$
- Since for independent distributions, their joint probability function is the multiplication of two independent probability functions. It can also be shown using 1-1 transformation that the joint distribution of R and θ is given by, 1-1 transformation:

Let $d=R^2$

$x= \sqrt {d}\cos \theta$
$y= \sqrt {d}\sin \theta$


then $\left| J\right| = \left| \dfrac {1} {2}d^{-\frac {1} {2}}\cos \theta d^{\frac{1}{2}}\cos \theta +\sqrt {d}\sin \theta \dfrac {1} {2}d^{-\frac{1}{2}}\sin \theta \right| = \dfrac {1} {2}$ It can be shown that the joint density of $d /R^2$ and $\theta$ is:

$\begin{matrix} f(d,\theta) = \frac{1}{2}e^{-\frac{d}{2}}*\frac{1}{2\pi},\quad d = R^2 \end{matrix},\quad for\quad 0\leq d\lt \infty\ and\quad 0\leq \theta\leq 2\pi$

Note that $\begin{matrix}f(r,\theta)\end{matrix}$ consists of two density functions, Exponential and Uniform, so assuming that r and $\theta$ are independent $\begin{matrix} \Rightarrow d \sim~ Exp(1/2), \theta \sim~ Unif[0,2\pi] \end{matrix}$

• \begin{align} R^2 = d = x^2 + y^2 \end{align}
• $\tan(\theta) = \frac{y}{x}$

\begin{align} f(d) = Exp(1/2)=\frac{1}{2}e^{-\frac{d}{2}}\ \end{align}
\begin{align} f(\theta) =\frac{1}{2\pi}\ \end{align}

To sample from the normal distribution, we can generate a pair of independent standard normal X and Y by:

1) Generating their polar coordinates
2) Transforming back to rectangular (Cartesian) coordinates.

Alternative Method of Generating Standard Normal Random Variables

Step 1: Generate $u_{1}$ ~$Unif(0,1)$
Step 2: Generate $Y_{1}$ ~$Exp(1)$,$Y_{2}$~$Exp(2)$
Step 3: If $Y_{2} \geq(Y_{1}-1)^2/2$,set $V=Y1$,otherwise,go to step 1
Step 4: If $u_{1} \leq 1/2$,then $X=-V$

===Expectation of a Standard Normal distribution===

The expectation of a standard normal distribution is 0

Proof:

$\operatorname{E}[X]= \;\int_{-\infty}^{\infty} x \frac{1}{\sqrt{2\pi}} e^{-x^2/2} \, dx.$
$\phi(x) = \frac{1}{\sqrt{2\pi}}\, e^{- \frac{\scriptscriptstyle 1}{\scriptscriptstyle 2} x^2}.$
$=\;\int_{-\infty}^{\infty} x \phi(x), dx.$
Since the first derivative ϕ′(x) is −(x)
$=\;\ - \int_{-\infty}^{\infty} \phi'(x), dx.$
$= - \left[\phi(x)\right]_{-\infty}^{\infty}$
$= 0$

Note, more intuitively, because x is an odd function (f(x)+f(-x)=0). Taking integral of x will give $x^2/2$ which is an even function (f(x)=f(-x)). This is in relation to the symmetrical properties of the standard normal distribution. If support is from negative infinity to infinity, then the integral will return 0.

Procedure (Box-Muller Transformation Method):

Pseudorandom approaches to generating normal random variables used to be limited. Inefficient methods such as inverse Gaussian function, sum of uniform random variables, and acceptance-rejection were used. In 1958, a new method was proposed by George Box and Mervin Muller of Princeton University. This new technique was easy to use and also had the accuracy to the inverse transform sampling method that it grew more valuable as computers became more computationally astute.
The Box-Muller method takes a sample from a bivariate independent standard normal distribution, each component of which is thus a univariate standard normal. The algorithm is based on the following two properties of the bivariate independent standard normal distribution:
if $Z = (Z_{1}, Z_{2}$) has this distribution, then

1.$R^2=Z_{1}^2+Z_{2}^2$ is exponentially distributed with mean 2, i.e.
$P(R^2 \leq x) = 1-e^{-x/2}$.
2.Given $R^2$, the point $(Z_{1},Z_{2}$) is uniformly distributed on the circle of radius R centered at the origin.
We can use these properties to build the algorithm:

1) Generate random number \begin{align} U_1,U_2 \sim~ \mathrm{Unif}(0, 1) \end{align}
2) Generate polar coordinates using the exponential distribution of d and uniform distribution of θ,

\begin{align} R^2 = d = -2\log(U_1), & \quad r = \sqrt{d} \\ & \quad \theta = 2\pi U_2 \end{align}

$\begin{matrix} \ R^2 \sim~ Exp(1/2), \theta \sim~ Unif[0,2\pi] \end{matrix}$

Note: If U~unif(0,1), then ln(1-U)=ln(U)

3) Transform polar coordinates (i.e. R and θ) back to Cartesian coordinates (i.e. X and Y),
\begin{align} x = R\cos(\theta) \\ y = R\sin(\theta) \end{align}
.

Alternatively,
$x =\cos(2\pi U_2)\sqrt{-2\ln U_1}\,$ and
$y =\sin(2\pi U_2)\sqrt{-2\ln U_1}\,$

Note: In steps 2 and 3, we are using a similar technique as that used in the inverse transform method.
The Box-Muller Transformation Method generates a pair of independent Standard Normal distributions, X and Y (Using the transformation of polar coordinates).

If you want to generate a number of independent standard normal distributed numbers (more than two), you can run the Box-Muller method several times.
For example:
If you want 8 independent standard normal distributed numbers, then run the Box-Muller methods 4 times (8/2 times).
If you want 9 independent standard normal distributed numbers, then run the Box-Muller methods 5 times (10/2 times), and then delete one.

Matlab Code

>>close all
>>clear all
>>u1=rand(1,1000);
>>u2=rand(1,1000);
>>d=-2*log(u1);
>>tet=2*pi*u2;
>>x=d.^0.5.*cos(tet);
>>y=d.^0.5.*sin(tet);
>>hist(tet)
>>hist(d)
>>hist(x)
>>hist(y)


Remember: For the above code to work the "." needs to be after the d to ensure that each element of d is raised to the power of 0.5.
Otherwise matlab will raise the entire matrix to the power of 0.5."

Note:
the first graph is hist(tet) and it is a uniform distribution.
The second one is hist(d) and it is a exponential distribution.
The third one is hist(x) and it is a normal distribution.
The last one is hist(y) and it is also a normal distribution.

Attention:There is a "dot" between sqrt(d) and "*". It is because d and tet are vectors.

As seen in the histograms above, X and Y generated from this procedure have a standard normal distribution.

• Code
>>close all
>>clear all
>>x=randn(1,1000);
>>hist(x)
>>hist(x+2)
>>hist(x*2+2)<br>


Note:
1. randn is random sample from a standard normal distribution.
2. hist(x+2) will be centered at 2 instead of at 0.
3. hist(x*3+2) is also centered at 2. The mean doesn't change, but the variance of x*3+2 becomes nine times (3^2) the variance of x.

Comment:
Box-Muller transformations are not computationally efficient. The reason for this is the need to compute sine and cosine functions. A way to get around this time-consuming difficulty is by an indirect computation of the sine and cosine of a random angle (as opposed to a direct computation which generates U and then computes the sine and cosine of 2πU.

Alternative Methods of generating normal distribution

1. Even though we cannot use inverse transform method, we can approximate this inverse using different functions.One method would be rational approximation.
2.Central limit theorem : If we sum 12 independent U(0,1) distribution and subtract 6 (which is E(ui)*12)we will approximately get a standard normal distribution.
3. Ziggurat algorithm which is known to be faster than Box-Muller transformation and a version of this algorithm is used for the randn function in matlab.

If Z~N(0,1) and X= μ +Zσ then X~$N(\mu, \sigma^2)$

If Z1, Z2... Zd are independent identically distributed N(0,1), then Z=(Z1,Z2...Zd)T ~N(0, Id), where 0 is the zero vector and Id is the identity matrix.

For the histogram, the constant is the parameter that affect the center of the graph.

### Proof of Box Muller Transformation

Definition:
A transformation which transforms from a two-dimensional continuous uniform distribution to a two-dimensional bivariate normal distribution (or complex normal distribution).

Let U1 and U2 be independent uniform (0,1) random variables. Then $X_{1} = ((-2lnU_{1})^.5)*cos(2\pi U_{2})$

$X_{2} = (-2lnU_{1})^0.5*sin(2\pi U_{2})$ are independent N(0,1) random variables.

This is a standard transformation problem. The joint distribution is given by

                  f(x1 ,x2) = fu1, u2(g1^− 1(x1,x2),g2^− 1(x1,x2)) * | J |


where J is the Jacobian of the transformation,

                  J = |∂u1/∂x1,∂u1/∂x2|
|∂u2/∂x1,∂u2/∂x2|


where

     u1 = g1 ^-1(x1,x2)
u2 = g2 ^-1(x1,x2)


Inverting the above transformation, we have

    u1 = exp^{-(x1 ^2+ x2 ^2)/2}
u2 = (1/2pi)*tan^-1 (x2/x1)


Finally we get

 f(x1,x2) = {exp^(-(x1^2+x2^2)/2)}/2pi


which factors into two standard normal pdfs.

(The quote is from http://mathworld.wolfram.com/Box-MullerTransformation.html) (The proof is from http://www.math.nyu.edu/faculty/goodman/teaching/MonteCarlo2005/notes/GaussianSampling.pdf)

### General Normal distributions

General normal distribution is a special version of the standard normal distribution. The domain of the general normal distribution is affected by the standard deviation and translated by the mean value.

• The pdf of the general normal distribution is
 $f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} }$ which is almost useless in this course

where $\mu$ is the mean or expectation of the distribution and $\sigma$ is standard deviation

The probability density must be scaled by 1/sigma so that the integral is still 1.(Acknowledge: https://en.wikipedia.org/wiki/Normal_distribution) The special case of the normal distribution is standard normal distribution, which the variance is 1 and the mean is zero. If X is a general normal deviate, then $Z=\dfrac{X - (\mu)}{\sigma}$ will have a standard normal distribution.

If Z ~ N(0,1), and we want $X$~$N(\mu, \sigma^2)$, then $X = \mu + \sigma * Z$ Since $E(x) = \mu +\sigma*0 = \mu$ and $Var(x) = 0 +\sigma^2*1$

If $Z_1,...Z_d$ ~ N(0,1) and are independent then $Z = (Z_1,..Z_d)^{T}$~ $N(0,I_d)$ ie.

• Code
>>close all
>>clear all
>>z1=randn(1,1000);    <-generate variable from standard normal distribution
>>z2=randn(1,1000);
>>z=[z1;z2];           <-produce a vector
>>plot(z(1,:),z(2,:),'.')


If Z~N(0,Id) and X= $\underline{\mu} + \Sigma^{\frac{1}{2}} \,Z$ then $\underline{X}$ ~$N(\underline{\mu},\Sigma)$

##### Non-Standard Normal Distributions

Example 1: Single-variate Normal

If X ~ Norm(0, 1) then (a + bX) has a normal distribution with a mean of $\displaystyle a$ and a standard deviation of $\displaystyle b$ (which is equivalent to a variance of $\displaystyle b^2$). Using this information with the Box-Muller transform, we can generate values sampled from some random variable $\displaystyle Y\sim N(a,b^2)$ for arbitrary values of $\displaystyle a,b$.

1. Generate a sample u from Norm(0, 1) using the Box-Muller transform.
2. Set v = a + bu.

The values for v generated in this way will be equivalent to sample from a $\displaystyle N(a, b^2)$distribution. We can modify the MatLab code used in the last section to demonstrate this. We just need to add one line before we generate the histogram:

v = a + b * x;


For instance, this is the histogram generated when b = 15, a = 125:

Example 2: Multi-variate Normal

The Box-Muller method can be extended to higher dimensions to generate multivariate normals. The objects generated will be nx1 vectors, and their variance will be described by nxn covariance matrices.

$\mathbf{z} = N(\mathbf{u}, \Sigma)$ defines the n by 1 vector $\mathbf{z}$ such that:

• $\displaystyle u_i$ is the average of $\displaystyle z_i$
• $\!\Sigma_{ii}$ is the variance of $\displaystyle z_i$
• $\!\Sigma_{ij}$ is the co-variance of $\displaystyle z_i$ and $\displaystyle z_j$

If $\displaystyle z_1, z_2, ..., z_d$ are normal variables with mean 0 and variance 1, then the vector $\displaystyle (z_1, z_2,..., z_d)$ has mean 0 and variance $\!I$, where 0 is the zero vector and $\!I$ is the identity matrix. This fact suggests that the method for generating a multivariate normal is to generate each component individually as single normal variables.

The mean and the covariance matrix of a multivariate normal distribution can be adjusted in ways analogous to the single variable case. If $\mathbf{z} \sim N(0,I)$, then $\Sigma^{1/2}\mathbf{z}+\mu \sim N(\mu,\Sigma)$. Note here that the covariance matrix is symmetric and nonnegative, so its square root should always exist.

We can compute $\mathbf{z}$ in the following way:

1. Generate an n by 1 vector $\mathbf{x} = \begin{bmatrix}x_{1} & x_{2} & ... & x_{n}\end{bmatrix}$ where $x_{i}$ ~ Norm(0, 1) using the Box-Muller transform.
2. Calculate $\!\Sigma^{1/2}$ using singular value decomposition.
3. Set $\mathbf{z} = \Sigma^{1/2} \mathbf{x} + \mathbf{u}$.

The following MatLab code provides an example, where a scatter plot of 10000 random points is generated. In this case x and y have a co-variance of 0.9 - a very strong positive correlation.

x = zeros(10000, 1);
y = zeros(10000, 1);
for ii = 1:10000
u1 = rand;
u2 = rand;
R2 = -2 * log(u1);
theta = 2 * pi * u2;
x(ii) = sqrt(R2) * cos(theta);
y(ii) = sqrt(R2) * sin(theta);
end

E = [1, 0.9; 0.9, 1];
[u s v] = svd(E);
root_E = u * (s ^ (1 / 2)) * u';

z = (root_E * [x y]');
z(1,:) = z(1,:) + 0;
z(2,:) = z(2,:) + -3;

scatter(z(1,:), z(2,:))


Note: The svd command computes the matrix singular value decomposition.

[u,s,v] = svd(E) produces a diagonal matrix s of the same dimension as E, with nonnegative diagonal elements in decreasing order, and unitary matrices u and v so that E = u*s*v'.

This code generated the following scatter plot:

In Matlab, we can also use the function "sqrtm()" or "chol()" (Cholesky Decomposition) to calculate square root of a matrix directly. Note that the resulting root matrices may be different but this does materially affect the simulation. Here is an example:

E = [1, 0.9; 0.9, 1];
r1 = sqrtm(E);
r2 = chol(E);


R code for a multivariate normal distribution:

n=10000;
r2<--2*log(runif(n));
theta<-2*pi*(runif(n));
x<-sqrt(r2)*cos(theta);

y<-sqrt(r2)*sin(theta);
a<-matrix(c(x,y),nrow=n,byrow=F);
e<-matrix(c(1,.9,09,1),nrow=2,byrow=T);
svde<-svd(e);
root_e<-svde$u %*% diag(svde$d)^1/2;
z<-t(root_e %*%t(a));
z[,1]=z[,1]+5;
z[,2]=z[,2]+ -8;
par(pch=19);
plot(z,col=rgb(1,0,0,alpha=0.06))


### Bernoulli Distribution

The Bernoulli distribution is a discrete probability distribution, which usually describes an event that only has two possible results, i.e. success or failure (x=0 or 1). If the event succeed, we usually take value 1 with success probability p, and take value 0 with failure probability q = 1 - p.

P ( x = 0) = q = 1 - p
P ( x = 1) = p
P ( x = 0) + P (x = 1) = p + q = 1

If X~Ber(p), its pdf is of the form $f(x)= p^{x}(1-p)^{(1-x)}$, x=0,1
P is the success probability.

The Bernoulli distribution is a special case of binomial distribution, where the variate x only has two outcomes; so that the Bernoulli also can use the probability density function of the binomial distribution with the variate x taking values 0 and 1.

The most famous example for the Bernoulli Distribution would be the "Flip Coin" question, which has only two possible outcomes(Success or Failure) with the same probabilities of 0.5

Let x1,x2 denote the lifetime of 2 independent particles, x1~exp($\lambda$), x2~exp($\lambda$) we are interested in y=min(x1,x2)


Procedure:

To simulate the event of flipping a coin, let P be the probability of flipping head and X = 1 and 0 represent

1. Draw U ~ Uniform(0,1)

2. If U <= P

X = 1

Else

X = 0

3. Repeat as necessary



An intuitive way to think of this is in the coin flip example we discussed in a previous lecture. In this example we set p = 1/2 and this allows for 50% of points to be heads or tails.

• Code to Generate Bernoulli(p = 0.3)
i = 1;

while (i <=1000)
u =rand();
p = 0.3;
if (u <= p)
x(i) = 1;
else
x(i) = 0;
end
i = i + 1;
end

hist(x)


However, we know that if \begin{align} X_i \sim Bernoulli(p) \end{align} where each \begin{align} X_i \end{align} is independent,
$U = \sum_{i=1}^{n} X_i \sim Binomial(n,p)$
So we can sample from binomial distribution using this property. Note: We can consider Binomial distribution as the sum of n, independent, Bernoulli distributions

• Code to Generate Binomial(n = 20,p = 0.7)
p = 0.7;
n = 20;

for k=1:5000
i = 1;
for i=1:n
u=rand();
if (u <= p)
y(i) = 1;
else
y(i) = 0;
end
end

x(k) = sum(y==1);
end

hist(x)



Note: We can also regard the Bernoulli Distribution as either a conditional distribution or $f(x)= p^{x}(1-p)^{(1-x)}$, x=0,1.

Comments on Matlab: When doing operations on vectors, always put a dot before the operator if you want the operation to be done to every element in the vector. example: Let V be a vector with dimension 2*4 and you want each element multiply by 3.

        The  Matlab code is 3.*V


some examples for using code to generate distribution.

## Class 7 - Tuesday, May 28

### Universality of the Uniform Distribution/Inverse Method

The inverse method is universal in the sense that we can potentially sample from any distribution where we can find the inverse of the cumulative distribution function.

Procedure:

1) Generate U~Unif (0, 1)
2) Set $x=F^{-1}(u)$
3) X~f(x)

Remark
1) The preceding can be written algorithmically for discrete random variables as
Generate a random number U ~ U(0,1]
If U < p0 set X = x0 and stop
If U < p0 + p1 set X = x1 and stop
...
2) If the xi, i>=0, are ordered so that x0 < x1 < x2 <... and if we let F denote the distribution function of X, then X will equal xj if F(xj-1) <= U < F(xj)

Example 1

Let $X$1,$X$2 denote the lifetime of two independent particles:
$X$1~exp($\lambda$1)
$X$2~exp($\lambda$2)

We are interested in $y=min(X$1$,X$2$)$
Design an algorithm based on the Inverse-Transform Method to generate samples according to $f$y$(y)$

Solution:

x1~exp($\lambda_1$)
x2~exp($\lambda_2$)
$f_{x(x)}=\lambda e^{-\lambda x},x\geq0$
$F_X(x)=1-e^{-\lambda x}, x\geq 0$

$1-F_Y(y) = P(Y\gt y)$ = P(min(X1,X2) > y) = $\, P((X_1)\gt y) P((X_2)\gt y) = e^{\, -(\lambda_1 + \lambda_2) y}$

$F_Y(y)=1-e^{\, -(\lambda_1 + \lambda_2) y}, y\geq 0$

$U=1-e^{\, -(\lambda_1 + \lambda_2) y}$ => $y=\, {-\frac {1}{{\lambda_1 +\lambda_2}}} ln(1-u)$

Procedure:

Step1: Generate U~ U(0, 1)

Step2: set $y=\, {-\frac {1}{{\lambda_1 +\lambda_2}}} ln(1-u)$

   or set $y=\, {-\frac {1} {{\lambda_1 +\lambda_2}}} ln(u)$


Since it is a uniform distribution, therefore after generate a lot of times 1-u and u are the same.

• Matlab Code
>> lambda1 = 1;
>> lambda2 = 2;
>> u = rand;
>> y = -log(u)/(lambda1 + lambda2)


If we generalize this example from two independent particles to n independent particles we will have:

$X$1~exp($\lambda$1)
$X$2~exp($\lambda$2)
...
$X$n~exp($\lambda$n)
.

And the algorithm using the inverse-transform method as follows:

step1: Generate U~U(0,1)

Step2: $y=\, {-\frac {1}{{ \sum\lambda_i}}} ln(1-u)$

Example 2
Consider U~Unif[0,1)
$X=\, a (1-\sqrt{1-u})$,
where a>0 and a is a real number What is the distribution of X?

Solution:

We can find a form for the cumulative distribution function of X by isolating U as U~Unif[0,1) will take values from the range of F(X)uniformly. It then remains to differentiate the resulting form by X to obtain the probability density function.

$X=\, a (1-\sqrt{1-u})$
=>$1-\frac {x}{a}=\sqrt{1-u}$
=>$u=1-(1-\frac {x}{a})^2$
=>$u=\, {\frac {x}{a}} (2-\frac {x}{a})$
$f(x)=\frac {dF(x)}{dx}=\frac {2}{a}-\frac {2x}{a^2}=\, \frac {2}{a} (1-\frac {x}{a})$

Example 3

Suppose FX(x) = xn, 0 ≤ x ≤ 1, n ∈ N > 0. Generate values from X.

Solution:

1. Generate $U ~\sim~ Unif[0, 1)$
2. Set $X = U^{1/n}$

For example, when $n = 20$,
$U = 0.6$ => $X = U^{1/20} = 0.974$
$U = 0.5 =\gt$ $X = U^{1/20} = 0.966$
$U = 0.2$ => $X = U^{1/20} = 0.923$

Observe from above that the values of X for n = 20 are close to 1, this is because we can view $X^n$ as the maximum of n independent random variables $X,$ $X~\sim~Unif(0,1)$ and is much likely to be close to 1 as n increases. This is because when n is large the exponent tends towards 0. This observation is the motivation for method 2 below.

Recall that If Y = max (X1, X2, ... , Xn), where X1, X2, ... , Xn are independent,
FY(y) = P(Y ≤ y) = P(max (X1, X2, ... , Xn) ≤ y) = P(X1 ≤ y, X2 ≤ y, ... , Xn ≤ y) = Fx1(y) Fx2(y) ... Fxn(y)
Similarly if $Y = min(X_1,\ldots,X_n)$ then the cdf of $Y$ is $F_Y = 1-$$\prod$$(1- F_{X_i})$

Method 1: Following the above result we can see that in this example, FX = xn is the cumulative distribution function of the max of n uniform random variables between 0 and 1 (since for U~Unif(0, 1), FU(x) =
Method 2: generate X by having a sample of n independent U~Unif(0, 1) and take the max of the n samples to be x. However, the solution given above using inverse-transform method only requires generating one uniform random number instead of n of them, so it is a more efficient method.

Generate the Y = max (X1, X2, ... , Xn), Y = min (X1, X2, ... , Xn), pdf and cdf, but (xi and xj are independent) i,j=1,2,3,4,5.....

Example 4 (New)
Now, we are having an similar example as example 1 just doing the maximum way.

Let X1,X2 denote the lifetime of two independent particles:
$\, X_1, X_2 \sim exp(\lambda)$

We are interested in Z=max(X1,X2)
Design an algorithm based on the Inverse-Transform Method to generate samples according to fZ(z)

$\, F_Z(z)=P[Z\lt =z] = F_{X_1}(z) \cdot F_{X_2}(z) = (1-e^{-\lambda z})^2$
$\text{thus } F^{-1}(z) = -\frac{1}{\lambda}\log(1-\sqrt z)$

To sample Z:
$\, \text{Step 1: Generate } U \sim U[0,1)$
$\, \text{Step 2: Let } Z = -\frac{1}{\lambda}\log(1-\sqrt U)$, therefore we can generate random variable of Z.

Discrete Case:

  u~unif(0,1)
x <- 0, S <- P0
while u < S
x <- x + 1
S <- S + P0
Return x


### Decomposition Method

The CDF, F, is a composition if $F_{X}(x)$ can be written as:

$F_{X}(x) = \sum_{i=1}^{n}p_{i}F_{X_{i}}(x)$ where

1) pi > 0

2) $\sum_{i=1}^{n}$pi = 1.

3) $F_{X_{i}}(x)$ is a CDF

The general algorithm to generate random variables from a composition CDF is:

1) Generate U,V ~ $Unif(0,1)$

2) If U < p1, V = $F_{X_{1}}(x)$-1

3) Else if U < p1 + p2, V = $F_{X_{2}}(x)$-1

4) Repeat from Step 1 (if N randomly generated variables needed, repeat N times)

Explanation
Each random variable that is a part of X contributes $p_{i} F_{X_{i}}(x)$ to $F_{X}(x)$ every time. From a sampling point of view, that is equivalent to contributing $F_{X_{i}}(x)$ $p_{i}$ of the time. The logic of this is similar to that of the Accept-Reject Method, but instead of rejecting a value depending on the value u takes, we instead decide which distribution to sample it from.

Simplified Version
1) Generate $u \sim Unif(0,1)$
2) Set $X=0, s=P_0$
3) While $u \gt s,$
set $X = X+1$ and $s=s+P_x$
4) Return $X$

### Examples of Decomposition Method

Example 1
$f(x) = \frac{5}{12}(1+(x-1)^4) 0\leq x\leq 2$
$f(x) = \frac{5}{12}+\frac{5}{12}(x-1)^4 = \frac{5}{6} (\frac{1}{2})+\frac {1}{6}(\frac{5}{2})(x-1))^4$
Let$f_{x_1}= \frac{1}{2}$ and $f_{x_2} = \frac {5}{2}(x-1)^4$

Algorithm: Generate U~Unif(0,1)
If $0\lt u\lt \frac {5}{6}$, then we sample from fx1
Else if $\frac{5}{6}\lt u\lt 1$, we sample from fx2
We can find the inverse CDF of fx2 and utilize the Inverse Transform Method in order to sample from fx2
Sampling from fx1 is more straightforward since it is uniform over the interval (0,2)

divided f(x) to two pdf of x1 and x2, with uniform distribution, of two range of uniform.

Example 2
$f(x)=\frac{1}{4}e^{-x}+2x+\frac{1}{12}, \quad 0\leq x \leq 3$
We can rewrite f(x) as $f(x)=(\frac{1}{4}) e^{-x}+(\frac{2}{4}) 4x+(\frac{1}{4}) \frac{1}{3}$
Let fx1 = $e^{-x}$, fx2 = 4x, and fx3 = $\frac{1}{3}$
Generate U~Unif(0,1)
If $0\lt u\lt \frac{1}{4}$, we sample from fx1

If $\frac{1}{4}\leq u \lt \frac{3}{4}$, we sample from fx2

Else if $\frac{3}{4} \leq u \lt 1$, we sample from fx3
We can find the inverse CDFs of fx1 and fx2 and utilize the Inverse Transform Method in order to sample from fx1 and fx2

We find Fx1 = $1-e^{-x}$ and Fx2 = $2x^{2}$
We find the inverses are $X = -ln(1-u)$ for Fx1 and $X = \sqrt{\frac{U}{2}}$ for Fx2
Sampling from fx3 is more straightforward since it is uniform over the interval (0,3)

In general, to write an efficient algorithm for:
$F_{X}(x) = p_{1}F_{X_{1}}(x) + p_{2}F_{X_{2}}(x) + ... + p_{n}F_{X_{n}}(x)$
We would first calculate ${q_i} = \sum_{j=1}^i p_j, \forall i = 1,\dots, n$ Then Generate $U \sim~ Unif(0,1)$
If $U \lt q_1$ sample from $f_1$
else if $u\lt q_i$ sample from $f_i$ for $1 \lt i \lt n$
else sample from $f_n$

when we divided the pdf of different range of f(x1) f(x2) and f(x3), and generate all of them and inverse, U~U(0,1)

### Example of Decomposition Method

$F_x(x) = \frac {1}{3} x+\frac {1}{3} x^2+\frac {1}{3} x^3, 0\leq x\leq 1$

Let $U =F_x(x) = \frac {1}{3} x+\frac {1}{3} x^2+\frac {1}{3} x^3$, solve for x.

$P_1=\frac{1}{3}, F_{x1} (x)= x, P_2=\frac{1}{3},F_{x2} (x)= x^2, P_3=\frac{1}{3},F_{x3} (x)= x^3$

Algorithm:

Generate $\,U \sim Unif [0,1)$

Generate $\,V \sim Unif [0,1)$

if $0\leq u \leq \frac{1}{3}, x = v$

else if $u \leq \frac{2}{3}, x = v^{\frac{1}{2}}$

else $x=v^{\frac{1}{3}}$

Matlab Code:

u=rand # U is
v=rand
if u<1/3
x=v
elseif u<2/3
x=sqrt(v)
else
x=v^(1/3)
end


=== Example of Decomposition Method(new) ===

Fx(x) = 1/2*x+1/2*x2, 0<= x<=1

let U =Fx(x) = 1/2*x+1/2*x2, solve for x.

P1=1/2, Fx1(x)= x, P2=1/2,Fx2(x)= x2,

Algorithm:

Generate U ~ Unif [0,1)

Generate V~ Unif [0,1)

if 0<u<1/2, x = v

else x = v1/2

Matlab Code:

u=rand
v=rand
if u<1/2
x=v
else
x=sqrt(v)
end


There are different types and applications of Decomposition Method

1. Primal decomposition

2. Dual decomposition

3. Decomposition with constraints

4. More general decomposition structures

5. Rate control

6. Single commodity network ﬂow

For More Details, please refer to http://www.stanford.edu/class/ee364b/notes/decomposition_notes.pdf

### Fundamental Theorem of Simulation

Consider two shapes, A and B, where B is a sub-shape (subset) of A. We want to sample uniformly from inside the shape B. Then we can sample uniformly inside of A, and throw away all samples outside of B, and this will leave us with a uniform sample from within B. (Basis of the Accept-Reject algorithm)

The advantage of this method is that we can sample a unknown distribution from a easy distribution. The disadvantage of this method is that it may need to reject many points, which is inefficient.
Inverse each part of partial CDF, the partial CDF is divided by the original CDF, partial range is uniform distribution.
More specific definition of the theorem can be found here.<ref>http://www.bus.emory.edu/breno/teaching/MCMC_GibbsHandouts.pdf</ref>

Matlab code:

close all
clear all
ii=1;
while ii<1000
u=rand
y=R*(2*U-1)
if (1-U^2)>=(2*u-1)^2
x(ii)=y;
ii=ii+1
end


### Question 2

Use Acceptance and Rejection Method to sample from $f_X(x)=b*x^n*(1-x)^n$ , $n\gt 0$, $0\lt x\lt 1$

Solution: This is a beta distribution, Beta ~$\int _{0}^{1}b*x^{n}*(1-x)^{n}dx = 1$

U1~Unif[0,1)

U2~Unif[0,1)

fx=$bx^{1/2}(1-x)^{1/2} \lt = bx^{-1/2}\sqrt2 ,0\lt =x\lt =1/2$

The beta distribution maximized at 0.5 with value $(1/4)^n$. So, $c=b*(1/4)^n$
Algorithm:
1.Draw $U_1$ from $U(0, 1)$. $U_2$ from $U(0, 1)$
2.If $U_2\lt =b*(U_1)^n*(1-(U_1))^n/b*(1/4)^n=(4*(U_1)*(1-(U_1)))^n$

 then X=U_1


Discrete Case: Most discrete random variables do not have a closed form inverse CDF. Also, its CDF $F:X \rightarrow [0,1]$ is not necessarily onto. This means that not every point in the interval $[0,1]$ has a preimage in the support set of X through the CDF function.

Let $X$ be a discrete random variable where $a \leq X \leq b$ and $a,b \in \mathbb{Z}$ .
To sample from $X$, we use the partition method below:

$\, \text{Step 1: Generate u from } U \sim Unif[0,1]$
$\, \text{Step 2: Set } x=a, s=P(X=a)$
$\, \text{Step 3: While } u\gt s, x=x+1, s=s+P(X=x)$
$\, \text{Step 4: Return } x$

## Class 8 - Thursday, May 30, 2013

In this lecture, we will discuss algorithms to generate 3 well-known distributions: Binomial, Geometric and Poisson. For each of these distributions, we will first state its general understanding, probability mass function, expectation and variance. Then, we will derive one or more algorithms to sample from each of these distributions, and implement the algorithms on Matlab.

### The Bernoulli distribution

The Bernoulli distribution is a special case of the binomial distribution, where n = 1. X ~ Bin(1, p) has the same meaning as X ~ Ber(p), where p is the probability of success and 1-p is the probability of failure (we usually define a variate q, q= 1-p). The mean of Bernoulli is p and the variance is p(1-p). Bin(n, p), is the distribution of the sum of n independent Bernoulli trials, Bernoulli(p), each with the same probability p, where 0<p<1.
For example, let X be the event that a coin toss results in a "head" with probability p, then X~Bernoulli(p).
P(X=1)= p P(X=0)= q = 1-p Therefore, P(X=0) + P(X=1) = p + q = 1

Algorithm:

1) Generate $u\sim~Unif(0,1)$
2) If $u \leq p$, then $x = 1$
else $x = 0$
when $U \leq p, x=1$
when $U \geq p, x=0$
3) Repeat as necessary

• Matlab Code
>> p = 0.8     % an arbitrary probability for example
>> for i = 1: 100
>>   u = rand;
>>   if u < p
>>       x(ii) = 1;
>>   else
>>       x(ii) = 0;
>>   end
>> end
>> hist(x)


### The Binomial Distribution

In general, if the random variable X follows the binomial distribution with parameters n and p, we write X ~ Bin(n, p). (Acknowledge: https://en.wikipedia.org/wiki/Binomial_distribution) If X ~ B(n, p), then its pmf is of form:

f(x)=(nCx) px(1-p)(n-x), x=0,1,...n
Or f(x) = $(n!/x!(n-x)!)$ px(1-p)(n-x), x=0,1,...n

Mean (x) = E(x) = $np$ Variance = $np(1-p)$

Generate n uniform random number $U_1,...,U_n$ and let X be the number of $U_i$ that are less than or equal to p. The logic behind this algorithm is that the Binomial Distribution is simply a Bernoulli Trial, with a probability of success of p, repeated n times. Thus, we can sample from the distribution by sampling from n Bernoulli. The sum of these n bernoulli trials will represent one binomial sampling. Thus, in the below example, we are sampling 1000 realizations from 20 Bernoulli random variables. By summing up the rows of the 20 by 1000 matrix that is produced, we are summing up the 20 bernoulli outcomes to produce one binomial sampling. We have 1000 rows, which means we have realizations from 1000 binomial random variables when this sum is done (the output of the sum is a 1 by 1000 sized vector).
To continue with the previous example, let X be the number of heads in a series of n independent coin tosses - where for each toss, the probability of coming up with a head is p - then X~Bin(n, p).
MATLAB tips: to get a pdf f(x), we can use code binornd(N,P). N means number of trials and p is the probability of success. a=[2 3 4],if set a<3, will produce a=[1 0 0]. If you set "a == 3", it will produce [0 1 0]. If a=[2 6 9 10], if set a<4, will produce a=[1 0 0 0], because only the first element (2) is less than 4, meanwhile the rest are greater. So we can use this to get the number which is less than p.

Algorithm for Bernoulli is given as above

Code

>>a=[3 5 8];
>>a<5
ans= 1 0 0

>>rand(20,1000)
>>rand(20,1000)<0.4
>>A = sum(rand(20,1000)<0.4)  #sum of raws ~ Bin(20 , 0.3)
>>hist(A)
>>mean(A)
Note: 1 in the above code means sum the matrix by column

>>sum(sum(rand(20,1000)<0.4)>8)/1000
This is an estimate of Pr[A>8].



remark: a=[2 3 4],if set a<3, will produce a=[1 0 0]. If you set "a == 3", it will produce [0 1 0]. using code to find some value what i want to get from the matrix. Its useful to defi