标题:求助 用辛普森积分法求二重积分 举个例子
只看楼主
c864433147
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2019-11-11
结帖率:0
已结贴  问题点数:20 回复次数:2 
求助 用辛普森积分法求二重积分 举个例子
搜索更多相关主题的帖子: 例子 积分 
2019-11-11 21:14
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:20 
先用 C++ 写一个,因为C++代码比较简单清晰
程序代码:
#include <functional>

double SimpsonIntegration1d( const std::function<double(double)>& f, double xa, double xb, unsigned n )
{
    double sum = f(xa) + f(xb);
    for( unsigned i=1; i<2*n; ++i )
        sum += (i%2*2+2) * f((xb-xa)/(2*n)*i+xa);
    return (xb-xa)/(6*n) * sum;
}

double SimpsonIntegration2d( const std::function<double(double,double)>& f, double xa, double xb, double ya, double yb, unsigned n )
{
    auto g = [=](double y) {
        auto h = [=](double x){ return f(x,y); };
        return SimpsonIntegration1d(h,xa,xb,n);
    };
    return SimpsonIntegration1d(g,ya,yb,n);
}

#include <stdio.h>

int main( void )
{
    auto f = [](double x, double y){ return x*x+y*y; };
    printf( "%f\n", SimpsonIntegration2d(f,-1,+1,-1,+1,1000) );
}

2019-11-12 10:22
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:0 
C语言没有 lambda,写起来比较繁琐

程序代码:
#include <stdio.h>

double SimpsonIntegration1d( double (*f)(double x), double xa, double xb, unsigned n )
{
    double sum = f(xa) + f(xb);
    for( unsigned i=1; i<2*n; ++i )
        sum += (i%2*2+2) * f((xb-xa)/(2*n)*i+xa);
    return (xb-xa)/(6*n) * sum;
}

double SimpsonIntegration2d_( double (*f)(double x,double y), double y, double xa, double xb, unsigned n )
{
    double sum = f(xa,y) + f(xb,y);
    for( unsigned i=1; i<2*n; ++i )
        sum += (i%2*2+2) * f((xb-xa)/(2*n)*i+xa,y);
    return (xb-xa)/(6*n) * sum;
}

double SimpsonIntegration2d( double (*f)(double x,double y), double xa, double xb, double ya, double yb, unsigned n )
{
    double sum = SimpsonIntegration2d_(f,ya,xa,xb,n) + SimpsonIntegration2d_(f,yb,xa,xb,n);
    for( unsigned i=1; i<2*n; ++i )
        sum += (i%2*2+2) * SimpsonIntegration2d_(f,(yb-ya)/(2*n)*i+ya,xa,xb,n);
    return (yb-ya)/(6*n) * sum;
}

#include <stdio.h>

double f( double x, double y )
{
    return x*x + y*y;
}

int main( void )
{
    printf( "%f\n", SimpsonIntegration2d(f,-1,+1,-1,+1,1000) );
}

2019-11-12 10:25



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-497742-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.056019 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved