ปัญหา
ได้รับสมการเชิงอนุพันธ์ f(x, y) = dy/dx พร้อมค่าเริ่มต้น y(x₀) = y₀ ต้องหาคำตอบโดยใช้วิธีออยเลอร์
วิธีออยเลอร์ (Euler Method)
เป็นขั้นตอนเชิงตัวเลขอันดับหนึ่ง (First-order numerical procedure) สำหรับหาคำตอบประมาณของสมการเชิงอนุพันธ์
สูตร:
y(n+1) = y(n) + h * f(x(n), y(n)) h = (x(n) - x(0)) / n (ขนาดขั้นตอน)
โปรแกรมตัวอย่าง
#include <iostream>
using namespace std;
float equation(float x, float y) {
return (x + y); // f(x,y) = 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