# PythonをRとの比較で練習する

```n <- 10
x <- sample(1:3,n,replace=TRUE)
x
mean(x)
1/n * sum(x)

x
tabulate(x)
w <- tabulate(x)/n
w
v <- sort(unique(x))
v
mw <- sum(v * w)
mw
>|python|
n = 10
import numpy as np

x = np.array(np.random.randint(1,4,n),dtype="f") # replace=TRUE is default
print x
print np.average(x)
print np.sum(x)/n
import collections
tab = collections.Counter(x)
print tab
m_w = 0.
for k,v in tab.items():
print k,v
m_w += k*v
print m_w/len(x)
```
```v <- 1:6
p <- rep(1/6,6)
sum(v*p)

v <- 1:6
p <- rep(1/6,6) + rnorm(6) * 0.1
p <- p/sum(p)
plot(v,p,type="h")
p
sum(p)
sum(v*p)
```
```import numpy as np
v = np.arange(1,7,dtype="f")
print v
p = np.repeat([1./6],6)
print p
print sum(v*p)

p += np.random.randn(6)*0.1
p /= np.sum(p)
print p
print np.sum(p)
print np.sum(v*p)
import matplotlib.pyplot as plt
#%pylab inline --no-import-all
plt.bar(np.arange(1,7),p)
#plt.show()
```
```p0 <- 0.3
n <- 10
i <- 0:n
i.inv <- i[(n+1):1]
choose(n,i)
p <- choose(n,i) * p0^i * (1-p0)^i.inv
plot(i,p,type="h")
sum(p)
sum(p*i)

n * p0
```
```import numpy as np
from scipy import special
p0 = 0.3
n = 10
i = np.arange(n+1)
print i
i_inv = i[::-1]
print i_inv
p = np.zeros(n+1)
for k in range(n+1):
p[k] = special.binom(n,k) * p0**i[k] * (1-p0)**i_inv[k]

print p
print special.binom(n,i) * p0**i * (1-p0)**i_inv
p = special.binom(n,i) * p0**i * (1-p0)**i_inv
print np.sum(p)
print np.sum(p*i)
```
```p <- seq(from=0,to=1,length=100)
h <- p
plot(p,h,type="l")
```
```import numpy as np
n = 100
p = np.arange(n+1,dtype="f")/n
print p
```
```n <- 3
m <- 5
p <- 0.2
gamma(n+m+2)/(gamma(n+1)*gamma(m+1))*p^n*(1-p)^m

dbeta(p,n+1,m+1)

p <- seq(from=0,to=1,length=100)
d <- dbeta(p,n+1,m+1)
plot(p,d,type="l")
```
```n = 3
m = 5
p = 0.2
from scipy import stats, special
print special.gamma(n+m+2)/(special.gamma(n+1)*special.gamma(m+1)) * p**n * (1-p)**m
print stats.beta.pdf(p,n+1,m+1)
import numpy as np
p = np.arange(101,dtype="f")/100
d = stats.beta.pdf(p,n+1,m+1)
#print d
import matplotlib.pyplot as plt
plt.plot(p,d)
plt.vlines(n/(n+m+0.),0,np.max(d))
plt.show()
```
```lambda <- 2.8
n <- 1000
x <- rpois(n,lambda)
plot(table(x))
mean(x)
```
```from scipy import stats
k = 2.8
n = 1000
x = stats.poisson.rvs(k,size=n)
#print x
import collections
tab = collections.Counter(x)
print tab
```
```ns <- 0:20
p <- lambda^ns/factorial(ns) * exp(-lambda)
plot(ns,p,type="h")

plot(ns,dpois(ns,lambda),type="h")
```
```import numpy as np
from scipy import misc, stats
ns = np.arange(21)
k = 2.8
p = k**ns/misc.factorial(ns) * np.exp(-k)
print p
import matplotlib.pyplot as plt
plt.bar(ns,p)
plt.show()
```
```n <- 4
lambdas <- seq(from=0,to=10,length=100)
L <- lambdas^n/factorial(n) * exp(-lambdas)
plot(lambdas,L,type="l")
plot(lambdas,log(L),type="l")
```
```import numpy as np
from scipy import special
n =4
k = np.arange(101)/100.*10
L = k**n/special.factorial(n) * np.exp(-k)
import matplotlib.pyplot as plt
plt.plot(k,L)
plt.show()
plt.plot(k,np.log(L))
plt.show()
```