Codes for P3
Note: a slight change was made to this program so it looks a little different from what is on the handout. (See the last few lines.) Basically, the program computes b(100,30) instead of b(550,30) as stated on the handout.
// P3A: Tests the methods in MyMath
import java.io.*;
public class P3A
{
public static void main(String args[])
{
TokenReader in = new TokenReader(System.in);
// The square root of 1,000,000.
double y = MyMath.sqrt(1000000.0);
Format.println(System.out,"The square root of one million = %20.15f", y);
// The absolute value of -10.
//double ten = MyMath.abs(-10.0);
//System.out.println("\nThe absolute value of -10 is " + ten);
// The absolute value of 10.
//ten = MyMath.abs(10.0);
//System.out.println("\nThe absolute value of 10 is " + ten);
// Number of poker hands
//long nPokerHands = MyMath.binCoeff(52,5);
//System.out.println("\nThe number of possible 5-card poker hands = " + nPokerHands);
//nPokerHands = MyMath.binCoeff(52,47);
//System.out.println("\nThe binomial coefficient 52-choose-47 = " + nPokerHands);
// Two-to-the-50.
//long twoE50 = (long) MyMath.pow(2,50);
//System.out.println("\nThe 50th power of two = " + twoE50);
// Stirling approximation to 5!
//double z = MyMath.stirling(5);
//System.out.println("\nThe Stirling approximation to 5! = " + z);
// Number of poker hands via Stirling
//long nPokerHandsApprx = (long) MyMath.binCoeffApprx(52,5);
//System.out.println("\nThe approximate number of 5-card poker hands = " + nPokerHandsApprx);
// The number of possible 30-student sections in a class of 100 students.
//double nSections = MyMath.binCoeffApprx(100,30);
//System.out.println("\nAn approximation to 100-choose-30 = " + nSections);
in.waitUntilEnter();
}
}
// This class contains methods that can be used to answer various
// combinatoric questions that involve binomial coefficients.
public class MyMath
{
public static final int KMAX = 12; // #Newton square root iterations.
// Yields the square root of x.
// The value of x must be nonnegative.
public static double sqrt(double x)
{
double y = x; // The current approximation to the square root.
int k;
// Perform KMAX steps of Newton's method.
for(k=1;k<=KMAX;k++)
{
y = (y+x/y)/2.0;
}
return y;
}
}