///////////////////////////////////////////////////////////////////////////
//                                                                       //
// Program file name: Lengendre.java                                     //
//                                                                       //
// © Tao Pang 2006                                                       //
//                                                                       //
// Last modified: January 18, 2006                                       //
//                                                                       //
// (1) This Java program is part of 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.     //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

// An example of using the Legendre polynomial generated. 

import java.lang.*;
import java.util.Random;
public class Legendre {
  public static void main(String argv[]) {
    int lmax = 5;
    Random r = new Random();
    double x = 2*(r.nextDouble()-0.5);

    double[] pl = p (x, lmax);
    for (int l=0; l<=lmax; ++l)
    System.out.println("p_" + l + " is: " + pl[l]);
  }

// Method to create the Legendre polynomials p_l(x) for
// a given x and maximum l.

  public static double[] p (double x, int lmax) {
    double pl[] = new double[lmax+1];
    pl[0] = 1;
    if (lmax==0) return pl;
    else {
      pl[1] = x;
      if (lmax==1) return pl;
      else {
        for (int l=1; l<lmax; ++l)
          pl[l+1] = ((2*l+1)*x*pl[l]
                   -(l+1)*pl[l-1])/(l+1);
        return pl;
      }
    }
  }
}
