added random stuff
[physik/computational_physics.git] / newton.c
1 /*
2  * newton'sche bewegungsgleichung
3  *
4  *
5  * usage: ./newton <steps> <alpha> <x_0> <v_0>
6  *
7  */
8
9 #include <stdio.h>
10 #include <string.h>
11 #include <math.h>
12 #include <stdlib.h>
13 #include "g_plot.h"
14
15 int main(int argc,char **argv) {
16  double x,x_p,v,v_p;
17  double alpha,force,tau;
18  int i,j,steps;
19  int fd; /* data file */
20  double *buf;
21  char filename[64];
22
23  if(argc!=5) {
24   printf("usage: %s <steps> <alpha> <x_0> <v_0>\n",argv[0]);
25   return -1;
26  }
27
28  /* init + starting conditions */
29  steps=atoi(argv[1]);
30  alpha=atof(argv[2]);
31  x_p=atof(argv[3]);
32  v_p=atof(argv[4]);
33  tau=2*M_PI/steps;
34  sprintf(filename,"newton_%d_%f_%f_%f.plot",steps,alpha,x_p,v_p);
35  fd=gp_init(filename);
36
37  /* allocate memory for data buffer */
38  if((buf=(double *)malloc(3*steps*sizeof(double)))==NULL) {
39   puts("malloc failed!");
40   return -1;
41  }
42  buf[0]=0; buf[1]=x_p; buf[2]=v_p;
43
44  /* loop */
45  for(i=0;i<steps-1;i++) {
46   force=-x_p-alpha*v_p;
47   x=x_p+v_p*tau;
48   v=v_p+force*tau; /* masse = 1 */
49   /* save */
50   j=3*i;
51   buf[3+j]=i*tau; buf[4+j]=x; buf[5+j]=v;
52   /* switch */
53   x_p=x; v_p=v;
54  }
55
56  /* write to file */
57  gp_add_data(fd,buf,3,steps,TYPE_DOUBLE);
58  gp_close(fd);
59
60  free(buf);
61
62  return 1;
63 }