/*************************    Program 2.B    ****************************/
/*                                                                      */
/************************************************************************/
/* Please Note:                                                         */
/*                                                                      */
/* (1) This computer program is written by Tao Pang in conjunction with */
/*     his book, "An Introduction to Computational Physics," published  */
/*     by Cambridge University Press in 1997.                           */
/*                                                                      */
/* (2) No warranties, express or implied, are made for this program.    */
/*                                                                      */
/************************************************************************/

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

main()
/* Program to fit the Millikan experimental data to a linear
   curve p(x) = a*x+b directly.  One can find a and b from
   partial D/partial a = 0 and partial D/partial b = 0 with
   D = sum (p(x_i)-f(x_i))**2.  The result is a = (c1*c3-
   c4*n)/(c1**2-c2*n) and b = (c1*c4-c2*c3)/(c1**2-c2*n) with
   n being the number of points, c1 = sum x_i, c2 = sum x_i**2,
   c3 = sum f(x_i), and c4 = sum x_i*f(x_i).
   Copyright (c) Tao Pang 1997. */
{
int i,n;
double c1,c2,c3,c4,a,b,c;
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};

n = 15;
c1 = 0;
c2 = 0;
c3 = 0;
c4 = 0;
for (i = 0; i < n; ++i)
  {
  c1 = c1+x[i];
  c2 = c2+x[i]*x[i];
  c3 = c3+f[i];
  c4 = c4+f[i]*x[i];
  }
c = c1*c1-c2*n;
a = (c1*c3-c4*n)/c;
b = (c1*c4-c2*c3)/c;
printf("The fundamental charge is %6.4lf +- %6.4lf\n", a,fabs(b));
}
