0

我很想用 C 语言制作速度 Verlet 方法。我以为我做得很好。但是,每当我增加向量或数组 x 和 y 的大小时,都会弹出“分段错误(核心转储)”。对于大小 n 等于且小于 1e3,这很好,但在 n = 1e4 时,程序会出错。

请任何人帮助我。谢谢你。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double verlet(double t, double x)
{

  double E = 0.252;
  double B = 0.052;
  double a = M_PI/2;

  return -sin(x) + E*cos(t) + B*cos(2*t+a); 
}   

double pverlet(double(*f)(double, double), double dt, double t, double x, double y)
{
    return  x + dt*( y + (dt/2)*f(t, x));
}

double vverlet(double(*g)(double, double), double dt, double t, double x,  double y)
{
    return y + (dt/2) * g(t, x); 
}

int main(void)
{
int i;
double t;

int n = 1e4;
double ti = 0, tf = 1e5, dt = (tf-ti)/n; 

double *x = (double *) malloc(sizeof(double)*n);
double *y = (double *) malloc(sizeof(double)*2*n);

if (x == NULL)
{
    printf("error allocating memory!\n");
    return 1;
}
if (y == NULL)
{
    printf("error allocating memory!\n");
    return 1;
}

for (y[0] = 0, i = 1; i <2*n; i++)
{
    y[i] = vverlet(verlet, dt, ti + dt*(i-1), x[i-1], y[i-1]);
}

for (x[0] = 0, i = 1; i < n; i++)
{
    x[i] = pverlet(verlet, dt, ti + dt*(i-1), x[i-1], y[2*(i-1)]);
}



for (i = 0; i < n; i++)
{
    t = ti + dt * i;
    printf("%e %e %e\n", t, x[i], y[2*i]);  

}

return 0;
free(x);
free(y);
}
4

1 回答 1

3
for (y[0] = 0, i = 1; i <2*n; i++)
{
    y[i] = vverlet(verlet, dt, ti + dt*(i-1), x[i-1], y[i-1]);
}

x 定义为从 0 到 n-1。

于 2015-04-07T01:26:59.477 回答