有人可以帮助我为此Python代码编写动画功能吗?

发布于 2025-01-22 16:51:47 字数 1041 浏览 2 评论 0原文

我正在尝试学习如何使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴骨ら 2025-01-29 16:51:47

这应该是一个很好的起点:

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()

This should be a good starting point:

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文