-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths09_stochasticsimulations.py
More file actions
69 lines (40 loc) · 1.01 KB
/
s09_stochasticsimulations.py
File metadata and controls
69 lines (40 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
"""S09-StochasticSimulations.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1BTPr5-vZZU7MU8LASzaTQrBQzUJsZLod
# Compute pi !
**Method 1: Use integrate from `scipy`**
"""
import scipy.integrate as intg
import math
def f(x):
return math.sqrt(1-x**2)
result = intg.quad(f,0,1)
print(result[0]*4)
"""**Method 2: Compute Integration**"""
import numpy as np
def f(x):
return np.sqrt(1-x**2)
d = 0.000001
x = np.arange(0,1+d,d)
y = f(x)
a = np.sum(d*y)*4
print(a)
"""**Stochastic computation**"""
import numpy as np
from numpy import random
n = 100_000_000
x = random.rand(n)*2-1
y = random.rand(n)*2-1
r = np.sqrt(x**2+y**2)
print(np.count_nonzero(r<=1)/n*4)
"""**QuantEcon: 8.14. A Mixed Discrete-Continuous Distribution**"""
import numpy.random as random
n = 10_000_000
t = random.rand(n)
x = np.zeros(n)
x[t<0.95] = 0
x[t>=0.95]=random.rand(len(t[t>=0.95]))*(400-300)+300
print(np.mean(x))
print(np.var(x))