我使用改进的欧拉方法编写了一个 C 代码,以定期确定振荡器的位置、速度和能量。但是,我遇到了一个问题,即振荡器的能量正在减少,尽管没有耗散项。我认为这与我更新位置和速度变量的方式特别相关,并希望得到您的帮助。我的代码如下:
//Compilation and run
//gcc oscillatorimprovedEuler.c -lm -o oscillatorimprovedEuler && ./oscillatorimprovedEuler
#include <stdio.h>
#include <math.h>
// The global constans are defined in the following way (having the constant value througout the program
#define m 1.0 // kg
#define k 1.0 // kg/sec^2
#define h 0.1 // sec This is the time step
#define N 201 // Number of time steps
int main(void)
{
// We avoid using arrays this time
double x = 0, xint = 0;
double v = 5, vint = 0; // Just like the previous case
double t = 0;
double E = (m * v * v + k * x * x) / 2.0; // This is the energy in units of Joules
FILE *fp = fopen("oscillatorimprovedEuler.dat", "w+");
int i = 0;
for(i = 0; i < N ; i++)
{
fprintf(fp, "%f \t %f \t %f \t %f \n", x, v, E, t);
xint = x + (h) * v;
vint = v - (h) * k * x / m;
v = v - (h) * ((k * x / m) + (k * xint / m)) / 2.0;
x = x + (h) * (v + vint) / 2.0;
E = (m * v * v + k * x * x) / 2.0;
t += h;
}
fclose(fp);
return 0;
}
我可能会错过一个非常轻微的观点,所以如果你能指出的话,我将不胜感激。我感谢您的帮助。