天天看點

HDU 1724 Ellipse——自适應simpson積分

題意:對于橢圓x^2/a^2+y^2/b^2 = 1(a,b已知),給定l,r,做直線x=l與x=r,求兩直線之間的橢圓部分的面積。

思路:正常積分不可積,考慮求近似解,即利用simpson積分求解。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

const double eps = 1e-10;
const double pi = acos(-1.0);
double a, b;

int dcmp(double x) {
    if (fabs(x) < eps) return 0;
    else return (x > 0 ? 1 : -1);
}
double f(double x) {
    return b*sqrt(1-x*x/(a*a));
}
double cal(double l, double r) {
    return (r-l)/6.0*(f(l)+f(r)+4.0*f((l+r)/2));
}
bool judge(double l, double r) {
    if(dcmp(cal(l, (l+r)/2) + cal((l+r)/2, r) - cal(l, r)) == 0) return true;
    else return false;
}
double dfs(double l, double r) {
    if (judge(l, r)) return cal(l, r);
    return dfs(l, (l+r)/2.0) + dfs((l+r)/2.0, r);
}

int main() {
    int n;
    double l, r;
    scanf("%d", &n);
    for (int kase = 1; kase <= n; kase++) {
        scanf("%lf%lf%lf%lf", &a, &b, &l, &r);
        printf("%.3f\n", 2.0*dfs(l, r));
    }
    return 0;
}