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 CurveMultiRoot(Scene):
    def construct(self):
        self.add(head("曲线交点：多个零点一次找出", "sp.nsolve / multi-start"))
        x = sp.symbols("x")
        roots = []
        for guess in (-3.0, -1.5, 1.5, 3.0):
            try:
                r = float(sp.nsolve(sp.sin(x) - x / 3, guess))
                if all(abs(r - q) > 0.05 for q in roots):
                    roots.append(r)
            except Exception:
                pass
        axes = Axes(x_range=[-4, 4, 1], y_range=[-2, 2, 1], x_length=9, y_length=4.8,
                    axis_config={"color": GREY_B}).shift(DOWN * 0.3)
        g1 = axes.plot(lambda t: np.sin(t), x_range=[-4, 4], color=BLUE).set_stroke(width=5)
        g2 = axes.plot(lambda t: t / 3, x_range=[-4, 4], color=GREEN).set_stroke(width=5)
        dots = VGroup(*[Dot(axes.c2p(r, np.sin(r)), color=RED, radius=0.14) for r in roots])
        lab = Text("roots = %d" % len(roots), font="Consolas", font_size=22,
                   color=GREY_A).to_corner(UR)
        self.add(axes, g1, g2, lab)
        self.play(LaggedStart(*[FadeIn(d, scale=2) for d in dots], lag_ratio=0.25),
                  run_time=2.4)
        self.play(FadeIn(foot("换不同初值多次求解，就能找齐全部交点")), run_time=0.4)
        self.wait(2.9)
