算法笔记--辛普森积分公式

一图胜千言。

自适应辛普森模板:

const double eps=1e-10;
double f(double x)
{
    //你的函数。 
} 
double simpson(double l,double r)
{
    return (f(l)+4.0*f((l+r)/2.0)+f(r))/6.0*(r-l);
}
double integral(double l,double r)
{
    double mid=(l+r)/2.0;
    double res=simpson(l,r);
    if(fabs(res-simpson(l,mid)-simpson(mid,r))<eps)return res;
    else return integral(l,mid)+integral(mid,r);
}

复合辛普森模板:

double f(double x) {
    double l = max(s1, x-w);
    double r = min(s2, x+w);
    if(r-l < eps) return eps;
    else return r-l;
}
double simpson(double l, double r) {
    return (f(l) + 4.0*f((l+r)/2.0) + f(r))/6.0*(r-l);
}
double integral(double l, double r) {
    double m = (l+r)/2.0;
    double res = simpson(l, r);
    if(fabs(res-simpson(l, m)-simpson(m, r)) < eps) return res;
    else return integral(l, m) + integral(m, r);
}
double fuhesimpson(double l, double r, int n) {
    double h = (r-l)/n, ans = 0;
    for (int i = 0; i < n; ++i) {
        ans += integral(l+i*h, l+(i+1)*h);
    }
    return ans;
}

参考:https://blog.csdn.net/tengweitw/article/details/43311685 

例题1:HDU 1724 Ellipse

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define pi acos(-1.0)
#define mem(a,b) memset(a,b,sizeof(a))

const double eps=1e-10;
double a,b;
double f(double x)
{
    return b*sqrt(1.0-(x*x)/(a*a)); 
} 
double simpson(double l,double r)
{
    return (f(l)+4.0*f((l+r)/2.0)+f(r))/6.0*(r-l);
}
double integral(double l,double r)
{
    double mid=(l+r)/2.0;
    double res=simpson(l,r);
    if(fabs(res-simpson(l,mid)-simpson(mid,r))<eps)return res;
    else return integral(l,mid)+integral(mid,r);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T;
    cin>>T;
    double l,r;
    while(T--)
    {
        cin>>a>>b>>l>>r;
        cout<<fixed<<setprecision(3)<<2*integral(l,r)<<endl;
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/widsom/p/7694882.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值