使用 C++ 求解微分方程的尤拉法


在本文中,我們將獲得一個微分方程f(x, y) = dy / dx 以及初始值y(x0) = y0。我們的任務是使用尤拉法解決該問題,求解微分方程。

尤拉法

尤拉法,又稱前向尤拉法,是一種一階數值程式,利用給定的初始值求解給定的微分方程。

對於微分方程 f(x, y) = dy / dx 尤拉法定義為:

y(n+1) = y(n) + h * f( x(n), y(n) )

h 的值為步長,計算公式為:

h = (x(n) - x(0)) / n

一個示例程式來說明我們解決方案的工作原理:

示例

現場演示

#include <iostream>
using namespace std;

float equation(float x, float y) {

   return (x + y);
}

void solveEquationEulers(float x0, float y, float h, float x) {

   float temp = 0.0;

   while (x0 < x) {
      temp = y;
      y = y + h * equation(x0, y);
      x0 = x0 + h;
   }
   cout<<"The solution of the differential equation at x = "<< x <<" is f(x, y) = "<<y;
}

int main()
{
   float x0 = 0;
   float y0 = 1;
   float h = 0.5;
   float x = 0.1;
   solveEquationEulers(x0, y0, h, x);
   return 0;
}

輸出 −

The solution of the differential equation at x = 0.1 is f(x, y) = 1.5

更新日期:22-Jan-2021

4K+ 檢視次數

開啟你的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.