```{r setup, include=FALSE}
library(reticulate)
# py_install("matplotlib")
# py_install("sympy")
knitr::opts_chunk$set(echo = TRUE)
```


# Symbolic computing inside Python  (inside R)

Will we explore basic symbolic computing inside Python.  In symbolic computing, the software is able to compute $2x = x+x$  or $\int_0^x x^2 dx = \tfrac{x^3}{3}$ *without* having a numerical value for $x$.  Popular software includes, Maple, Mathematica, and Sage; Python's *sympy* is a basic in-house substitute, which we will explore.


```{python}
import sympy as sym

x = sym.pi   # the digit pi
print(x)
print("#############")
print(x.evalf())
print("#############")
print(x.evalf(100))
print("#############")

x = sym.Symbol('x')   # you got to tell Python that x is symbol
print(sym.simplify((x + x)))

y = sym.Symbol('y')
y=sym.integrate(3 * x ** 2, x)  # integrate 3x^2
print(y)
print("#############")
```

We can also do linear algebra

```{python}
a = sym.Symbol('a')
b = sym.Symbol('b')
c = sym.Symbol('c')
d = sym.Symbol('d')
M =  sym.Symbol('M')
M=sym.Matrix([[a, b], [c, d]])
print(M)
print("#############")
print(M.det())
print("#############")
print(M.T)
print("#############")
print(M.eigenvects())
print("#############")
Msub = M.subs(a,1).subs(b,1).subs(c,1).subs(d,0)
values = Msub.eigenvects()
print("#############")
print(values)
print("#############")


```





# A Markov chain

Consider the three state Markov chain on $\{1,2,3\}$ where 
$$p_{11} = p = 1-p_{12}$$ 
$$p_{22} = q=1- p_{23}$$
and
$$p_{31}=1.$$

We will consider the case where $q \in (0,1)$ is fixed, but will think of $p \to 1$.  

* Write down the transition matrix.

* Suppose the Markov chain $X$ with these transition probabilities starts in state $1$.  Let $T = \inf\{n \geq 1: X_n = 1\}$.   Compute (by brute force) $\mathbb{E}(T)$.

* Find the stationary distribution of the transition matrix.

*  Simulate the chain, and leave $p$ and $q$ as variables that you can choose.

*  See that all your findings and answers are consistent.


#  Endnotes

* Version: `r format(Sys.time(), '%d %B %Y')`
* [Rmd Source](https://tsoo-math.github.io/ucl2/returntime.Rmd)
<br>
<br>
<br>
