前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >函数式编程计算数值积分

函数式编程计算数值积分

作者头像
fem178
发布2021-09-15 15:09:43
1.1K0
发布2021-09-15 15:09:43
举报
文章被收录于专栏:数值分析与有限元编程

以函数式编程方式,计算数值积分。

定积分的定义点击这里:定积分的精确定义

下面以定积分

I = \int_0^3 (x^3-6x)dx\,.

为例,展示过程。

如图所示,将积分区间6等分,每一个子区间长度为0.5,则数值积分值为

最终结果与精确值的误差为

(6.75-3.9375)/6.75=41.6\%

python代码

代码语言:javascript
复制
steps = 6  #积分区间六等分
a = 0.0
b = 3.0

dx = (b-a)/steps  #每个子区间长度

f = lambda x: x**3 - 6*x #积分函数

#构造{0,1,2,3,4,5}
r = range(steps) 

#{0,1,2,3,4,5}映射成为{0.5,1.0,1.5,2.0,2.5,3}

map_r1 = map(lambda x: (x+1)*dx, r) 

# 子区间右端点函数值,即每个矩形的高度
map_h = map(f, map_r1)

int = dx * sum(map_h)
print(int)

如果将积分区间500等分,计算结果为-6.723,相对误差为

(6.75-6.723)/6.75=0.4\%

Python代码:

代码语言:javascript
复制
steps = 500  #积分区间500等分
a = 0.0
b = 3.0

dx = (b-a)/steps  #每个子区间长度

f = lambda x: x**3 - 6*x #积分函数

#构造{0,1,2,3,4,5,...,500}
r = range(steps) 

map_r1 = map(lambda x: (x+1)*dx, r) 

# 子区间右端点函数值,即每个矩形的高度
map_h = map(f, map_r1)

int = dx * sum(map_h)
print(int)

采用同样思路的C++代码(需要支持C++20标准的编译器)

代码语言:javascript
复制
#include <iostream>
#include <ranges>
#include<numeric>

using namespace std::ranges::views;

int main(){   
    constexpr auto steps {500} ;
    constexpr auto a {0.0};
    constexpr auto b {3.0};
    constexpr auto dx { (b-a)/steps }; // 
    constexpr auto f_cubic = [](double x){return x*(x*x) - 6*x;};
    
    constexpr auto r_int {iota(0, steps)} ; // 
    constexpr auto r_pos {r_int | transform([dx](int i){return dx*(0.5 + i);}) }; 
    
    constexpr auto r_cubic{ r_pos | transform(f_cubic)} ; 
    // 
    constexpr auto res {dx* std::accumulate(r_cubic.begin(), r_cubic.end(), 0.0)} ; 
    // 
    std::cout << "积分结果为:" << res << std::endl;
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数值分析与有限元编程 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档