我试图编写代码来解决二阶ODE,但由于某种原因,它无法正常工作。
等式为2y“+ 5y'+ 3y = 0,y(0)= 3和y'(0)= -4
最终答案将是y(x)= 3-4x <
因此y(1)= -1和y'(1)= -4
但是程序输出为y(1)= 0.81414 y'(1)= -1.03727 <
请帮忙!
谢谢!
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <math.h>
double ddx(double x,double y,double z)
{
double dx = (-5*z-3*y)/2;
return dx;
}
double test2ndorder(double x0, double y0, double z0, double xt, double h)
{
int n = (int)((xt - x0) / h);
double k1, k2, k3, k4;
double l1, l2, l3, l4;
double x = x0;
double y = y0;
double z = z0;
for (int i = 1; i <= n; i++)
{
k1 = h * z;
l1 = h * ddx(x, y, z);
k2 = h * (z + 0.5*l1);
l2 = h * ddx(x + 0.5*h, y + 0.5*k1, z + 0.5*l1);
k3 = h * (z + 0.5*l2);
l3 = h * ddx(x + 0.5*h, y + 0.5*k2, z + 0.5*l2);
k4 = h * (z + l3);
l4 = h * ddx(x + h, y + k3, z + l3);
y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4);
z = z + (1.0 / 6.0)*(l1 + 2 * l2 + 2 * l3 + l4);
x = x + h;
std::cout << y << " ";
std::cout << z << "\n";
}
return y;
}
int main()
{
double x0, y0, z0, x, y, z,h;
x0 = 0;
x = 1;
y0 = 3;
z0 = -4;
h =0.01;
y = test2ndorder(x0, y0, z0, x, h);
std::cout << y;
}
最佳答案
2y" + 5y' +3y = 0 ,y(0) = 3 and y'(0) = -4
具有特征根源,是
(2r)^2 + 5*(2r) + 6 = 0 <==> r = -1 or r = -1.5
所以解决方案是
y(x) = A*exp(-x)+B*exp(-1.5*x)
3 = y(0) = A + B
-4 = y'(0) = -A - 1.5*B
这样的
B = 2
和A = 1
y(1) = 0.814139761468302
y'(1) = -1.03726992161673
这是关于你得到的。
关于c++ - Runge-Kutta使用C++求解四阶ODE的四阶,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49041945/