// ch05a_simpson.cpp —— 实验 5.1：数值积分方法大比拼（含 SVG 误差图）
// 数学：梯形法误差 O(h²)、辛普森法误差 O(h⁴)
// 积分：∫[0,1] e^{−x²} dx ≈ 0.7468241328124271（概率积分，无初等原函数！）
#include "svgplot.hpp"
#include <cstdio>
#include <cmath>
#include <vector>

double g(double x) { return std::exp(-x * x); }

double trapezoid(int n) {
    double h = 1.0 / n, s = 0.5 * (g(0) + g(1));
    for (int i = 1; i < n; ++i) s += g(i * h);
    return s * h;
}

double simpson(int n) {               // n 取偶数
    double h = 1.0 / n, s = g(0) + g(1.0);
    for (int i = 1; i < n; ++i) s += (i % 2 ? 4.0 : 2.0) * g(i * h);
    return s * h / 3.0;
}

int main() {
    const double EXACT = 0.7468241328124271;
    printf("== 实验 5.1 梯形法 vs 辛普森法：∫[0,1] e^(−x²) dx ==\n\n");
    printf("（被积函数没有初等原函数 —— 数值积分是唯一出路）\n\n");
    printf("%8s %14s %14s %14s %14s\n",
           "n", "梯形结果", "梯形误差", "辛普森结果", "辛普森误差");
    printf("------------------------------------------------------------\n");

    std::vector<std::pair<double, double>> eT, eS;
    int ns[] = {4, 8, 16, 32, 64, 128, 256};
    for (int n : ns) {
        double t = trapezoid(n), s = simpson(n);
        double et = std::fabs(t - EXACT), es = std::fabs(s - EXACT);
        printf("%8d %14.10f %14.3e %14.10f %14.3e\n", n, t, et, s, es);
        eT.push_back({std::log2((double)n), std::log10(et)});
        eS.push_back({std::log2((double)n), std::log10(es)});
    }
    printf("\n观察：n 加倍 → 梯形误差 ÷4（斜率 −2），辛普森误差 ÷16（斜率 −4）。\n");
    printf("      同样的函数求值次数，辛普森快两个数量级 —— 阶数决定效率。\n");

    // ---- SVG：log-log 误差图 ----
    SvgPlot pl(1.8, 8.4, -13.5, -1.0, 680, 400);
    pl.open("ch05a_simpson.svg");
    pl.axes("log2 n", "log10 误差");
    pl.plot(eT, "#003b5c", 1.8, "", "梯形法（O(h²)）");
    pl.plot(eS, "#b23a2e", 2.2, "", "辛普森法（O(h⁴)）");
    pl.legend();
    pl.close();
    printf("\n已生成 ch05a_simpson.svg（误差收敛 log-log 图）\n");
    return 0;
}
