使用C++编制常微分方程初值问题的欧拉法、改进的欧拉法和经典的R-K法的程序;
时间: 2023-12-20 07:05:05 浏览: 78
欧拉法程序:
#include <stdio.h>
double f(double x, double y) {
return x + y;
}
int main() {
double x, y, h;
int i, n;
printf("请输入初值 x0 和 y0:");
scanf("%lf%lf", &x, &y);
printf("请输入步长 h 和计算次数 n:");
scanf("%lf%d", &h, &n);
for (i = 0; i < n; i++) {
printf("x%d = %f, y%d = %f\n", i, x, i, y);
y += h * f(x, y);
x += h;
}
printf("x%d = %f, y%d = %f\n", i, x, i, y);
return 0;
}
改进的欧拉法程序:
#include <stdio.h>
double f(double x, double y) {
return x + y;
}
int main() {
double x, y, h, k1, k2;
int i, n;
printf("请输入初值 x0 和 y0:");
scanf("%lf%lf", &x, &y);
printf("请输入步长 h 和计算次数 n:");
scanf("%lf%d", &h, &n);
for (i = 0; i < n; i++) {
printf("x%d = %f, y%d = %f\n", i, x, i, y);
k1 = h * f(x, y);
k2 = h * f(x + h, y + k1);
y += 0.5 * (k1 + k2);
x += h;
}
printf("x%d = %f, y%d = %f\n", i, x, i, y);
return 0;
}
经典的R-K法程序:
#include <stdio.h>
double f(double x, double y) {
return x + y;
}
int main() {
double x, y, h, k1, k2, k3, k4;
int i, n;
printf("请输入初值 x0 和 y0:");
scanf("%lf%lf", &x, &y);
printf("请输入步长 h 和计算次数 n:");
scanf("%lf%d", &h, &n);
for (i = 0; i < n; i++) {
printf("x%d = %f, y%d = %f\n", i, x, i, y);
k1 = h * f(x, y);
k2 = h * f(x + 0.5 * h, y + 0.5 * k1);
k3 = h * f(x + 0.5 * h, y + 0.5 * k2);
k4 = h * f(x + h, y + k3);
y += 1.0 / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4);
x += h;
}
printf("x%d = %f, y%d = %f\n", i, x, i, y);
return 0;
}
阅读全文
相关推荐
















