数值计算 - Richardson外推法求一阶导数(C++实现)

本文介绍了使用Richardson外推法来求解一阶导数的方法,并提供了C++实现代码,适用于数值计算场景。
摘要由CSDN通过智能技术生成

求导只需将 f 中的函数替换即可。

/*本程序使用理查森外推方法就求微分,程序的核心是运用G[i][j] =
 (pow(4, i) * G[i][j-1] - G[i-1][j-1])/(pow(4, i)-1)*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double le = 1e-10;


template <typename T> T** Allocation2D(int m, int n){
	T **a;
	a = new T*[m];
	for(int i=0; i<m; i++)
		a[i] = new T[n];
	return a;
}


double f(double x);
void WaiTui(double t, double h);
void Clear(double **G, int m);

int main(){
	double t, h;
	cout<<"请输入所求值的导数:";
	cin>>t;
	cout<<"请输入步长的值:";
	cin>>h;
	WaiTui(t, h);
	return 0;
}


/********************************函数f = sin(x)/x *******************************/
double f(double x){
	double result;
	result = sin(x)/x;
	return result;
}


void WaiTui(double t, double h){
	int i, k = 0;
	double **G;
	G = Allocation2D<double>(10, 10);	
	G[0][0] = (f(t + h) - f(t - h))
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Richardson外推法提高一阶双曲方程的Lax-Friedrich格式的精度的matlab代码: ```matlab % 定义参数 a = 1; % 双曲方程中的常数 dx = 0.1; % 空间步长 dt = 0.01; % 时间步长 T = 1; % 模拟时间 x = 0:dx:1; % 空间网格 t = 0:dt:T; % 时间网格 N = length(x); % 空间网格数 M = length(t); % 时间网格数 r = a*dt/dx; % 稳定性参数 % 初始条件 u0 = sin(pi*x); u = u0; % Lax-Friedrich格式 for n = 2:M un = u; for i = 2:N-1 u(i) = 0.5*(un(i+1) + un(i-1)) - 0.5*r*(un(i+1) - un(i-1)); end u(1) = un(2) - r*(u(2) - un(1)); u(N) = un(N-1) + r*(un(N) - u(N-1)); end lax_friedrich = u; % Richardson外推法 for n = 2:M un = u; for i = 2:N-1 u(i) = 0.5*(un(i+1) + un(i-1)) - 0.5*r*(un(i+1) - un(i-1)); end u(1) = un(2) - r*(u(2) - un(1)); u(N) = un(N-1) + r*(un(N) - u(N-1)); u_richardson = (4*u - un)/3; end % 计算误差 error = abs(lax_friedrich - u_richardson); % 绘图 figure; subplot(1,2,1); plot(x, lax_friedrich, 'b', x, u_richardson, 'r'); title('Lax-Friedrich格式和Richardson外推法结果'); legend('Lax-Friedrich格式', 'Richardson外推法'); subplot(1,2,2); plot(x, error); title('误差'); ``` 以上代码中,首先定义了双曲方程中的常数$a$,空间步长$dx$,时间步长$dt$,模拟时间$T$,空间网格$x$,时间网格$t$,空间网格数$N$,时间网格数$M$,以及稳定性参数$r$。然后定义了初始条件$u_0$和初始解$u$。接下来使用Lax-Friedrich格式求解一阶双曲方程,并使用Richardson外推法提高精度,并计算误差。最后绘制了Lax-Friedrich格式和Richardson外推法的结果,并绘制了误差图。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值