我正在嘗試學習如何為使用 montecarlo 方法計算函式積分的圖表制作影片,但沒有成功。我對python了解不多,這是我幾年前除了學習一些語言基礎之外的第一個代碼。這是我到目前為止所寫的。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
N = 100000
print("N=", N)
x_list = []
y_list = []
x_list.append(np.random.uniform(low=-5, high=5, size=[N, 1]))
y_list.append(np.random.uniform(low=0, high=2, size=[N, 1]))
x = np.array(x_list)
y = np.array(y_list)
ins = y - np.exp((-x**2) / 2) < 0
ap_pi = 20 * np.sum(ins) / N
print('pi: {}, approximation: {}'.format(np.pi, ap_pi))
print(ap_pi)
x_in = x[ins]
y_in = y[ins]
fig = plt.figure(figsize=[10, 10])
plt.text(1, 2.145, "Value of the integral:", fontsize=14)
plt.text(4, 2.15, ap_pi, bbox=dict(facecolor='red', alpha=0.5))
plt.scatter(x_list, y_list, s=1)
plt.scatter(x_in, y_in, color='r', s=1)
def animation(i):
anim = FuncAnimation(fig, animation, frames=100, interval=20)
plt.pause(0.01)
plt.show()
我確實嘗試將 plt.scatter 移動到影片功能,但這只會導致以某種方式對顏色進行影片處理。我也嘗試了多種東西,但最終打開了圖表本身的回圈。我不知道如何進行。有什么幫助嗎?
uj5u.com熱心網友回復:
這應該是一個很好的起點:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
N = 100000
print("N=", N)
x = np.random.uniform(-5, 5, N)
y = np.random.uniform(0, 2, N)
ins = y - np.exp((-x**2) / 2) < 0
ap_pi = 20 * np.sum(ins) / N
print('pi: {}, approximation: {}'.format(np.pi, ap_pi))
print(ap_pi)
x_in = x[ins]
y_in = y[ins]
def animation(i):
line1.set_data(x[:i], y[:i])
if i < len(x_in):
# remember that len(x_in) < N
line2.set_data(x_in[:i], y_in[:i])
fig = plt.figure(figsize=[10, 10])
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(-5, 5)
ax.set_ylim(0, 2)
ax.text(1, 2.145, "Value of the integral:", fontsize=14)
ax.text(4, 2.15, ap_pi, bbox=dict(facecolor='red', alpha=0.5))
# initialize empty scatter plots. They will receive updated data below.
# NOTE: I'm using `ax.plot` because I know what method I have to call
# when updating data. If I use `ax.scatter`, who knows... :|
line1, = ax.plot([], [], 'o')
line2, = ax.plot([], [], 'o', color='r')
# The length of the animation is given by N
anim = FuncAnimation(fig, animation, frames=N, interval=20)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461108.html
標籤:Python matplotlib matplotlib-动画
上一篇:在python中繪制大資料集集群
