summaryrefslogtreecommitdiff
path: root/fun_math
diff options
context:
space:
mode:
authorzhang <zch921005@126.com>2022-08-21 09:41:53 +0800
committerzhang <zch921005@126.com>2022-08-21 09:41:53 +0800
commit94b6d3246c72eb3cae58a2fd18771e3c2c3e7cb2 (patch)
treee23a287289cdca8020fab062cdebffa60b021d7f /fun_math
parent756b736ca374dc6ef2adadce101f380e10f06c4e (diff)
copy
Diffstat (limited to 'fun_math')
-rw-r--r--fun_math/r_w.py66
-rw-r--r--fun_math/random_walk.py14
2 files changed, 80 insertions, 0 deletions
diff --git a/fun_math/r_w.py b/fun_math/r_w.py
new file mode 100644
index 0000000..c1eb3ed
--- /dev/null
+++ b/fun_math/r_w.py
@@ -0,0 +1,66 @@
+
+import matplotlib.pyplot as plt
+import matplotlib.animation as animation
+import numpy as np
+
+np.random.seed(1234)
+
+
+def random_walk(N):
+ """
+ Simulates a discrete random walk
+ :param int N : the number of steps to take
+ """
+ # event space: set of possible increments
+ increments = np.array([1, -1])
+ # the probability to generate 1
+ p = 0.5
+
+ # the epsilon values
+ random_increments = np.random.choice(increments, N, p)
+ # calculate the random walk
+ random_walk = np.cumsum(random_increments)
+
+ # return the entire walk and the increments
+ return random_walk, random_increments
+
+
+# generate a random walk
+N = 500
+X, epsilon = random_walk(N)
+
+# normalize the random walk using the Central Limit Theorem
+# X = X * np.sqrt(1. / N)
+
+fig = plt.figure(figsize=(21, 10))
+ax = plt.axes(xlim=(0, N), ylim=(np.min(X) - 0.5, np.max(X) + 0.5))
+line, = ax.plot([], [], lw=2, color='#0492C2')
+ax.set_xticks(np.arange(0, N+1, 50))
+ax.set_yticks(np.arange(np.min(X) - 0.5, np.max(X) + 0.5, 0.2))
+ax.set_title('2D Random Walk', fontsize=22)
+ax.set_xlabel('Steps', fontsize=18)
+ax.set_ylabel('Value', fontsize=18)
+ax.tick_params(labelsize=16)
+ax.grid(True, which='major', linestyle='--', color='black', alpha=0.4)
+
+# initialization function
+def init():
+ # creating an empty plot/frame
+ line.set_data([], [])
+ return line,
+
+# lists to store x and y axis points
+xdata, ydata = [], []
+
+# animation function
+def animate(i):
+ y = X[i]
+ # appending new points to x, y axes points list
+ xdata.append(i)
+ ydata.append(y)
+ line.set_data(xdata, ydata)
+ return line,
+
+# call the animator
+anim = animation.FuncAnimation(fig, animate, init_func=init, frames=N, interval=20, blit=True)
+anim.save('random_walk.gif',writer='imagemagick') \ No newline at end of file
diff --git a/fun_math/random_walk.py b/fun_math/random_walk.py
new file mode 100644
index 0000000..b425fcb
--- /dev/null
+++ b/fun_math/random_walk.py
@@ -0,0 +1,14 @@
+
+import random
+
+
+# N, S, W, E
+choices = [(0, 1), (0, -1), (-1, 0), (1, 0)]
+
+
+def rand_walk(n, p0=[]):
+ if p0 is None:
+ p0 = [0, 0]
+ pass
+
+