一、写在前面
数值积分之后,就应该是数值微分了,还是老套路,表明实验内容后,直接上代码,思想都在注释之中。
实验内容:
二、实验过程
对数值微分的思想有了一定的掌握,根据算法最基本的公式来写
三、实验结果
【参考代码】
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double Derivativefunction(double x, double y) //导函数表达式
{
return y-2*x/y;
}
double function(double x) //原函数
{
return sqrt(1 + 2*x);
}
void Euler(double a, double b, double initialValue, int n)
//Euler算法,在区间[a, b]上,初值f(a) = initialValue, n等分
{
int i = 0;
double x = a;
double y = initialValue;
double h = (b-a)/n; //步长
for(i=1; i<=n; i++)
{
printf("x = %lf:\t", x+h);
y = y + h*Derivativefunction(x, y);
printf("y(Euler) = %lf\t", y);
x += h;
printf("y(准确) = %lf\n", function(x));
}
}
void ImprovementEuler(double a, double b, double initialValue, int n)
//ImprovementEuler算法,传入参数与Euler函数同理
//从Euler算法复制并加以修改
{
int i = 0;
double x = a;
double yForecast; //y预测
double temp = initialValue;
double yCorrecting; //校正
double h = (b-a)/n; //步长
for(i=1; i<=n; i++)
{
printf("x = %lf:\t", x+h);
yForecast = temp + h*Derivativefunction(x, temp);
yCorrecting = temp + (Derivativefunction(x, temp) + \
Derivativefunction(a+h*i, yForecast))*h/2;
temp = yCorrecting;
printf("y(ImprovementEuler) = %lf\t", temp);
x += h;
printf("y(准确) = %lf\n", function(x));
}
}
void FourOrderRung_Kutta(double a, double b, double initialValue, int n) //四阶Rung_Kutta算法
{
int i = 0;
double x = a;
double y = initialValue;
double h = (b-a)/n; //步长
double K1, K2, K3, K4;
for(i=1; i<=10; i++)
{
printf("x = %lf:\t", x+h);
K1 = Derivativefunction(x, y);
K2 = Derivativefunction(x+h/2, y+K1*h/2);
K3 = Derivativefunction(x+h/2, y+K2*h/2);
K4 = Derivativefunction(x+h, y+K3*h);
y += (K1+2*K2+2*K3+K4)*h/6;
printf("y(FourOrderRung_Kutta) = %lf\t", y);
x += h;
printf("y(准确) = %lf\n", function(x));
}
}
int main()
{
printf("------------------------Euler----------------------\n");
Euler(0, 1, 1, 10);
printf("\n-------------------ImprovementEuler----------------\n");
ImprovementEuler(0, 1, 1, 10);
printf("\n-----------------FourOrderRung_Kutta---------------\n");
FourOrderRung_Kutta(0, 1, 1, 10);
return 0;
}
四、写在后面
数值微分的实际应用:
在许多科学技术问题中,建立的模型常常以常微分方程的形式表示。然而,除了少数特殊类型的常微分方程能用解析方法求其精确解外,要给出一般方程解析解的表达式是困难的。所以只能用近似方法求其数值解,在实际工作中常用计算机求常微分方程的数值解。所谓常微分方程的数值解即对于常微分方程初值问题
计算出在一系列节点 a = x0< x1<…< xn= b 处的未知函数 y(x)近似值y0,y1,…yn,即找到一系列离散点(x0,y0)(x1,y1)(x2,y2)…(xn,yn)近似满足常微分方程。数值解法的基本思想用差商代替导数,实现连续问题离散化,选取不同的差商代替导数可以得到不同公式。