// ch12c_taylor_svg.cpp —— 实验 12.3：泰勒多项式的逼近图（生成 SVG）
// 数学：T_n(x) = Σ_{k=0}^{n} x^k/k!（e^x 的 n 阶泰勒多项式）
// 图形：n 越大，T_n 在更宽的区间上贴合 e^x —— “局部逼近，全局扩张”
#include "svgplot.hpp"
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>

double taylor(double x, int n) {
    double term = 1.0, sum = 1.0;
    for (int k = 1; k <= n; ++k) { term *= x / k; sum += term; }
    return sum;
}

int main() {
    printf("== 实验 12.3 e^x 的泰勒多项式逼近（绘图程序）==\n\n");

    // 采样：x ∈ [−2.5, 2.5]
    std::vector<std::pair<double, double>> fx, t1, t3, t5, t7;
    for (int i = 0; i <= 200; ++i) {
        double x = -2.5 + 5.0 * i / 200.0;
        fx.push_back({x, std::exp(x)});
        t1.push_back({x, taylor(x, 1)});
        t3.push_back({x, taylor(x, 3)});
        t5.push_back({x, taylor(x, 5)});
        t7.push_back({x, taylor(x, 7)});
    }

    SvgPlot pl(-2.5, 2.5, -2.0, 8.5, 680, 420);
    pl.open("ch12c_taylor.svg");
    pl.axes("x", "y");
    pl.plot(t7, "#7d5a2f", 1.2, "3,3", "7 阶");
    pl.plot(t5, "#b23a2e", 1.2, "3,3", "5 阶");
    pl.plot(t3, "#003b5c", 1.2, "3,3", "3 阶");
    pl.plot(t1, "#8a8578", 1.2, "3,3", "1 阶（切线）");
    pl.plot(fx, "#141414", 2.4, "", "e^x");
    pl.legend();
    pl.close();

    // 数值补充：中心 x=0 处各阶最大误差（在 |x|≤1 上）
    printf("在 [−1, 1] 上的最大逼近误差：\n");
    printf("%6s %14s\n", "阶数 n", "max |T_n − e^x|");
    printf("----------------------\n");
    for (int n : {1, 3, 5, 7, 9}) {
        double emax = 0.0;
        for (int i = 0; i <= 400; ++i) {
            double x = -1.0 + 2.0 * i / 400.0;
            emax = std::max(emax, std::fabs(taylor(x, n) - std::exp(x)));
        }
        printf("%6d %14.3e\n", n, emax);
    }
    printf("\n已生成 ch12c_taylor.svg：虚线为各阶多项式，实线为 e^x。\n");
    printf("观察：1 阶只在 0 点附近像切线；7 阶已把 e^x 抱在怀里 ——\n");
    printf("      “阶数换宽度”，这正是函数展开成级数的意义。\n");
    return 0;
}
