有人可以帮助我为此Python代码编写动画功能吗?
我正在尝试学习如何使用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移至动画函数,但这只会使颜色以某种方式进行动画。我还尝试了多个东西,但最终以打开图本身的循环。我不知道该如何进行。有帮助吗?
I am trying to learn how to animate this graph that calculates the integral of a function using the montecarlo method but to no success. I don't have much understanding of python, this is my first code besides learning some language basics a few years ago. This is what I wrote so far.
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()
I did try moving plt.scatter to the animation function but this only resulted in animating the colors somehow. I also tried multiple stuff but ended up with loops of opening the graph itself. I have no idea how to proceed towards this. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该是一个很好的起点:
This should be a good starting point: