/*************************************************************************/
/* Program file name: millikan2.c                                        */
/*                                                                       */
/* © Tao Pang 2006                                                       */
/*                                                                       */
/* Last modified: June 15, 2006                                          */
/*                                                                       */
/* (1) This C program is created for the book, "An Introduction to       */
/*     Computational Physics, 2nd Edition," written by Tao Pang and      */
/*     published by Cambridge University Press on January 19, 2006.      */
/*                                                                       */
/* (2) No warranties, express or implied, are made for this program.     */
/*                                                                       */
/*************************************************************************/

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

/* An example of directly fitting the Millikan data to
   p1(x)=a0+a1*x. */


main() {
  int i, n = 14;
  double c1, c2, c3, c4, g, a0, a1;
  double x[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                15, 16, 17, 18};
  double f[] = {6.558, 8.206, 9.880, 11.50, 13.14, 14.81,
                16.40, 18.04, 19.68, 21.32, 22.96, 24.60,
                26.24, 27.88, 29.52};
  c1 = 0;
  c2 = 0;
  c3 = 0;
  c4 = 0;
  for (i=0; i<=n; ++i) {
    c1 += x[i];
    c2 += x[i]*x[i];
    c3 += f[i];
    c4 += f[i]*x[i];
  }
  g = c1*c1-c2*(n+1);
  a0 = (c1*c4-c2*c3)/g;
  a1 = (c1*c3-c4*(n+1))/g;
  printf("Fundamental charge: %6.4lf\n", a1);
  printf("Estimated error: %6.4lf\n", a0);
}
