c ++中的Euler方法

时间:2017-09-26 23:25:09

标签: c++

以下代码使用欧拉方法逼近y(x)的值。我的代码当前接受端点a和b作为用户输入,并且α值的值是初始条件,步长值是h。鉴于我的代码,我现在可以近似y的值,假设y(8)给定初始条件y(0)= 6。

但是我的代码中有一个小错误,我不太确定如何修复它并正在寻求帮助。现在我的代码没有检查以确保正确的端点b是步长h的整数倍。由于这个原因,最终的近似可能不是针对f(b)而是针对f(c),其中c是h与b的最接近的整数倍。我正在寻找一些如何解决这个问题的帮助,谢谢!

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

double dydx (double x, double y)
    {
        double f = y*(2-y)/(x+3);
        return f;
    }
int main()
{
    double a,b,alpha,h,z;
    cout<<"\nEnter the value of endpoint a: \n";
    cin>>a;
    cout<<"\nEnter the value of endpoint b: \n";
    cin>>b;
    cout<<"\nEnter the y value of the initial condition: \n";
    cin>>alpha;
    cout<<"\nEnter the stepsize, h: \n";
    cin>>h;
    cout<<"\n";
    while((b-a)>0.0000001)
    {
        z=alpha+(h*dydx(a,alpha));
        cout<<"z("<<a<<")="<<z<<endl;
        alpha=z;
        a=a+h;
    }
    cout<<"\nThe approximate solution of y("<<b<<") is "<<z<<"."<<endl;
    return 0;
}

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以根据步骤h计算步长n

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

double dydx (double x, double y)
    {
        double f = y*(2-y)/(x+3);
        return f;
    }
int main()
{
    double a,b,alpha,h,z;
    cout<<"\nEnter the value of endpoint a: \n";
    cin>>a;
    cout<<"\nEnter the value of endpoint b: \n";
    cin>>b;
    cout<<"\nEnter the y value of the initial condition: \n";
    cin>>alpha;
    /*
     * Obtains step size from number on steps
     * h = 0.1 for [a; b] = [0; 8] can be given by n = 80
    */
    int n = 0;
    cout<<"\nEnter the number of steps, n: \n";
    cin>>n;
    h = (b - a) / n;
    //------
    cout<<"\n";
    //-- Replaced 0.0000001 by h / 2.0 --
    while((b-a)> h / 2.0)
    {
        z=alpha+(h*dydx(a,alpha));
        alpha=z;
        a=a+h;
        /* 
         * z - function value in next point, 
         * so to output correct point a need to be incremented before this.   
        */
        cout<<"z("<<a<<")="<<z<<endl;
    }
    cout<<"\nThe approximate solution of y("<<b<<") is "<<z<<"."<<endl;
    return 0;
}

插入此而不是h输入。