from manim import *
import numpy as np
import sympy as sp
def head(cn, en):
    t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
    s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
    return VGroup(t, s)
def foot(cn):
    return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
class DerivativeTangent(Scene):
    def construct(self):
        self.add(head("导数：割线逼近切线", "SymPy / diff / ValueTracker"))
        x = sp.symbols("x")
        f = x**3 - 2*x + 1
        df = sp.diff(f, x)
        fy = sp.lambdify(x, f, "numpy")
        slope = float(df.subs(x, 1))
        y1 = float(f.subs(x, 1))
        axes = Axes(x_range=[-2.5, 2.5, 1], y_range=[-3, 5, 1], x_length=8, y_length=5,
                    axis_config={"color": GREY_B}).shift(DOWN * 0.3)
        graph = axes.plot(lambda t: fy(t), x_range=[-2.1, 2.1], color=BLUE).set_stroke(width=5)
        h = ValueTracker(1.8)
        sec = always_redraw(lambda: Line(
            axes.c2p(1, y1),
            axes.c2p(1 + h.get_value(), fy(1 + h.get_value())),
            color=YELLOW).set_stroke(width=5))
        tangent = Line(axes.c2p(-1.2, y1 + slope * (-2.2)),
                       axes.c2p(2.2, y1 + slope * 1.2), color=RED).set_stroke(width=5)
        lab = Text("slope = %.2f" % slope, font="Consolas", font_size=22,
                   color=GREY_A).to_corner(UR)
        self.add(axes, graph, sec, lab)
        self.play(h.animate.set_value(0.18), run_time=3.4)
        self.play(Create(tangent), run_time=1.4)
        self.play(FadeIn(foot("h 趋近 0 时割线斜率收敛到导数值")), run_time=0.4)
        self.wait(1.2)
