数值分析 欧拉预估矫正公式

img


欧拉预估矫正公式,但是没有确定方程
要怎么写一个通用编程,适用于各种方程呢?

基于Monster 组和GPT的调写:

#include <stdio.h>
#include <math.h>

double f(double x, double y)
{
    // 此处为待求解的方程,需要根据实际问题进行修改
    return x * y - x * y * y;
}

void euler(double x0, double y0, double h, double xf)
{
    double x = x0;
    double y = y0;
    double y_pred, y_corr;
    while (x <= xf)
    {
        printf("%.4lf %.4lf\n", x, y);
        y_pred = y + h * f(x, y);
        y_corr = y + h * (f(x, y) + f(x + h, y_pred)) / 2.0;
        y = y_corr;
        x += h;
    }
}

int main()
{
    double x0, y0, xf, h;
    printf("Enter the initial value of x: ");
    scanf("%lf", &x0);
    printf("Enter the initial value of y: ");
    scanf("%lf", &y0);
    printf("Enter the final value of x: ");
    scanf("%lf", &xf);
    printf("Enter the step size h: ");
    scanf("%lf", &h);

    euler(x0, y0, h, xf);
    return 0;
}


需要修改的部分是函数f,该函数表示待求解的方程。根据不同的问题,需要修改函数中的表达式。例如,对于欧拉预估-校正公式的示例问题,可以将f函数修改为:

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


不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^