mp.set_start_method('spawn',True)# see https://github.com/microsoft/ptvsd/issues/1443
fromnumbaimportjit
```
%% Cell type:markdown id: tags:
## Random walk on $\mathbb{Z}$
Consider the random walk on $\mathbb{Z}$ with $0 < p < 1$, denoted by $(S_n)$. The chain is supposed to start from state 0.
%% Cell type:markdown id: tags:
1\. Implement a function `random_walk_z` simulating the behaviour of the random walk for $n_{\max}$ steps. #
2\. Modify the function `random_walk_z` such that it further returns: #
- both the number of times the chain is returned to the initial state;
- the largest state reached by the chain.
%% Cell type:code id: tags:
``` python
@jit(nopython=True)
deffind_first(item,vec):
"""
find_first: find the index of the first element in the array `vec` equal to the element `item`.
:param item: elemtns against which the entries of `vec` are compared
:type item: int or double
:param vec: [description]
:type vec: array-like
:return: index of the first element in `vec` equal to `item`
:rtype: int
"""
foriinrange(len(vec)):
ifitem==vec[i]:
returni
return-1
defrandom_walk_z(p,X0,n_max,random_state):
""" Simulate a simple 1D random walk in Z.
Input:
------
:param p:
Transition probability (:math:`0 < p <1`)
:type p:
float
:param X0:
Initial state opf the chain.
:type X0:
int
:param n_max:
Maximal number of time steps.
:type n_max:
int
Output:
-------
:param random_state:
Random generator or seed to initialize it.
:type random_state:
None | int | instance of RandomState
:returns:
- X (array-like) - trajectory of the chain
- Ti (:py:class:`int`) - return time to the initial state
- state_max (:py:class:`int`) - farthest state reached by the chain (w.r.t the initial state)
"""
rng=check_random_state(random_state)
Z=2*rng.binomial(1,p,size=(n_max))-1
X=np.empty(shape=(n_max+1),dtype=float)
X[0]=X0
X[1:]=X0+np.cumsum(Z)
Ti=find_first(0,X[1:])+1
id=np.argmax(np.abs(X))
state_max=X[id]
returnX,Ti,state_max
```
%% Cell type:markdown id: tags:
3\. Simulate the random walk with $p = 3/4$, and display the histogram of the states reached by the chain. Do the same with $p=1/2$ and illustrate the central limit theorem stated in the lecture, ie: $\lim_{n\to\infty} n^{-1/2}S_n$ is distributed as a standard normal random variable.
%% Cell type:code id: tags:
``` python
# to do
```
%% Cell type:markdown id: tags:
4\. Assume now that two players $A$ and $B$ play heads or tails, where heads occur with probability $p$. Player $A$ bets $1$ euro on heads at each toss, and $B$ bets $1$ euro on tails. Assume that:
- the initial fortune of $A$ is $a \in \mathbb{N}$;
- the initial fortune of $B$ is $b\in\mathbb{N}$;
- the gain ends when a player is ruined.
Implement a function which returns the empirical frequency of winning for $A$, and compare it with the theoretical probability computed in the lecture.