要找 的最小值点,可以用 numpy 直接算,再让一个点沿着曲线滑过去。示例用 np.linspace 采样、argmin() 取最小索引,ValueTracker 驱动点的位置。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from manim import *
import numpy as np
class ArgMinExample(Scene):
def construct(self):
ax = Axes(
x_range=[0, 10], y_range=[0, 100, 10], axis_config={"include_tip": False}
)
labels = ax.get_axis_labels(x_label="x", y_label="f(x)")
t = ValueTracker(0)
def func(x):
return 2 * (x - 5) ** 2
graph = ax.plot(func, color=MAROON)
initial_point = [ax.coords_to_point(t.get_value(), func(t.get_value()))]
dot = Dot(point=initial_point)
dot.add_updater(lambda x: x.move_to(ax.c2p(t.get_value(), func(t.get_value()))))
x_space = np.linspace(*ax.x_range[:2],200)
minimum_index = func(x_space).argmin()
self.play(*[FadeIn(_o) for _o in [ax, labels, graph, dot]], run_time=1.0)
self.play(t.animate.set_value(x_space[minimum_index]))
self.wait()
self.wait(2.60)

演示视频

下载 Python 脚本

要点

  • ax.c2p(x, y) 把数学坐标转成画面坐标,是坐标轴场景的高频方法
  • np.argmin() 返回最小值的下标,再用采样数组取对应 x
  • dot.add_updater 里用 move_to 跟随,比每帧重建 Dot 省资源

代码来源:Manim Community 官方 Example Gallery 示例 ArgMinExample(MIT),已在 Manim CE 0.20.1 实跑验证并生成上方视频。