ExpTrend.java0100640000203700000250000000351707243273370013360 0ustar pmelbysfiguestimport corejava.*; class ExpTrend { public ExpTrend(Position x, double d, double p, double c, double l) { equity = x; weight = d; newp = p; coeff = c; margin = l; int i; double price; double oldprice; double expectation; } // end ExpTrend init public void setPrice(double newprice) { oldprice = newprice; price = newprice; expectation = 0.0; } public void updatePrice(double newprice) { oldprice = price; price = newprice; } public void updateMargin(double newmargin) { margin = newmargin; } public void updatePosition(double order) { equity.updatePosition(order, price); } public void printoutWealth() { equity.printWealth(price); } public double getProfits() { double profits; double holdings; double money; double wealth; double initmoney = Math.exp(8.0); holdings = equity.getHoldings(); money = equity.getMoney(); wealth = money + Math.exp(price)*holdings; profits = (wealth - initmoney)/initmoney; return profits; } public double placeOrder() { double order; double wants; double realequity; realequity = equity.getHoldings(); double money = equity.getMoney(); double w = money + Math.exp(price)*realequity; w = w/price; expectation = (1.0-weight)*expectation + weight*(price-oldprice); wants = coeff*(expectation); //wants = coeff*MathUtil.tanh(2.0*expectation); //wants = w*MathUtil.tanh(2.0*expectation); order = wants - realequity; return order; } // end placeOrder private Position equity; private double weight; private double newp; private double coeff; private double margin; private double price; private double oldprice; private int i; private double expectation; } // end ValueInvestor class MarketMaker.java0100640000203700000250000000274207243273373014034 0ustar pmelbysfiguestclass MarketMaker { public MarketMaker(double l, Position x, double p, double k) {equity = x; liquidity = l; price = p; kickback = k; initialliquidity = liquidity; } //end MarketMaker init public double getPrice(double totalorders) { double newprice; newprice = price + (1.0/liquidity)*totalorders; return newprice; } //end getPrice public void updatePrice(double newprice) { price = newprice; } public void updatePosition(double totalorder) { totalorder = -1.0*totalorder; equity.updatePosition(totalorder, price); } public double placeOrder() { double holdings; double order; holdings = equity.getHoldings(); order = -1.0*kickback*holdings; return order; } public void printoutWealth() { equity.printWealth(price); } public double getProfits() { double profits; double holdings; double money; double wealth; double initmoney = Math.exp(8.0); holdings = equity.getHoldings(); money = equity.getMoney(); wealth = money + Math.exp(price)*holdings; profits = (wealth - initmoney)/initmoney; return profits; } public void changeLiquidity(double volume) { liquidity = initialliquidity/(0.001*volume+1.0); } private double orders; private Position equity; private double liquidity; private double price; private double kickback; private double initialliquidity; private double initequity; } // end MarketMaker class MarketSim6.java0100640000203700000250000002626407243273374013621 0ustar pmelbysfiguestimport java.lang.*; import corejava.*; import java.io.*; import java.util.*; public class MarketSim6 { public static void main(String args[]) { int i; int j; int N=2; int totaltime = 10000; // double[] orders; double[] actualorder; Position[] standing = new Position[N]; Position[] trendstanding = new Position[N]; double[] orders = new double[N]; double[] actualorder = new double[N]; double[] b = new double[totaltime/2]; double[] a = new double[totaltime/2]; double[] aval = new double[totaltime/2]; double[] bval = new double[totaltime/2]; double dcval = 0.0; double[] valpow = new double[totaltime/2]; double[] acorr = new double[totaltime/2]; double[] bcorr = new double[totaltime/2]; double[] powerspectrum = new double[totaltime/2]; double pricenoise = 0.00; double[] pricenoisea = new double[totaltime/2]; double[] pricenoiseb = new double[totaltime/2]; double[] pricepow = new double[totaltime/2]; double[] smoothpricepow = new double[totaltime/2]; double[] pricefilter = new double[totaltime/2]; double freqindex = 0.0; double filteradd = 0.0; double periodindex; double oldprice = 1.0; double dc; double inside; double pi = Math.PI; // 4.0*Math.atan(1.0); double noiselevel = 0.0; double makerorder; double volatility = 0.0; double volume; int fouriertop = (totaltime - 1)/2; int fouriertop2 = (fouriertop - 1)/2; double[] autopower = new double[totaltime/2]; double[] corrcalc = new double[totaltime/2]; double lambda = 10000.0; double c_constant = 800.0; double c_constant2 = 0.0; double alpha = 2*c_constant/lambda; double beta = 0.0; double mispricing; double noiseorder; double[] mispricinga = new double[totaltime/2]; double[] mispricingb = new double[totaltime/2]; double[] mispricingcorr = new double[totaltime/2]; double[] mispower = new double[totaltime/2]; double[] smoothvalp = new double[totaltime/2]; double[] smoothretp = new double[totaltime/2]; double[] filter = new double[totaltime/2]; double[] volumea = new double[totaltime/2]; double[] volumeb = new double[totaltime/2]; double[] volumecorr = new double[totaltime/2]; double[] volumepow = new double[totaltime/2]; double misdc = 0.0; double miscorrdc = 0.0; double volumedc = 0.0; double volumecorrdc = 0.0; int k; double corrdc=0.0; int[] delay = new int[N]; delay[0] = 10; delay[1] = 10; double[] trendorders = new double[N]; double[] actualtrendorder = new double[N]; double[] trendprofits = new double[N]; double[] valueprofits = new double[N]; double makerprofits; double oldreturns = 0.0; Random randnum = new Random(12381); for (j=1; j <= fouriertop; j++) {a[j] = 0.0; b[j] = 0.0;acorr[j] = 0.0;bcorr[j] = 0.0; autopower[j] = 0.0; aval[j] = 0.0; bval[j] = 0.0; smoothretp[j] = 0.0; smoothvalp[j] = 0.0; filter[j] = 0.0; mispricinga[j] = 0.0;mispricingb[j] = 0.0; mispricingcorr[j] = 0.0;mispower[j] = 0.0; pricenoisea[j] = 0.0; pricenoiseb[j] = 0.0; pricepow[j] = 0.0; smoothpricepow[j] = 0.0; pricefilter[j] = 0.0; volumea[j] = 0.0;volumeb[j] = 0.0;volumecorr[j] = 0.0; volumepow[j] = 0.0; } dc = 0.0; for (j = 0; j < N; j++) {standing[j] = new Position(0.0,0.0,8.0); trendstanding[j] = new Position(0.0,0.0,8.0); } Position makerstanding = new Position(0.0, 0.0, 8.0); // Position trendstanding = new Position(0.0,0.0, 8.0); double price = 1.0; double newprice; double[] value = new double[N]; double totalorder; double valueadd; for (j = 0; j < N; j++) { value[j] = 1.0; } // ValueInvestor trader = new ValueInvestor(standing, value, price, 10.0, 0.5); ValueInvestor[] trader = new ValueInvestor[N]; for (j=0; j < N; j++) { trader[j] = new ValueInvestor(standing[j], value[j], price, c_constant, 0.99999); } TrendFollower[] trender = new TrendFollower[N]; //ExpTrend[] trender = new ExpTrend[N]; for (j=0; j < N; j++) { // trender[j] = new ExpTrend(trendstanding[j], 1.0, price, c_constant2, 0.9999); trender[j] = new TrendFollower(trendstanding[j], delay[j], price, c_constant2, 0.99999); trender[j].setPrice(price); } MarketMaker maker = new MarketMaker(lambda, makerstanding, price, beta); for (i=0; i < totaltime; i++) { totalorder = 0; volume = 0.0; mispricing = price - value[1]; for(j = 0; j < N; j++) {orders[j] = trader[j].placeOrder(); trendorders[j] = trender[j].placeOrder(); totalorder = totalorder + orders[j] + trendorders[j]; } // end for j makerorder = maker.placeOrder(); totalorder = totalorder + makerorder; newprice = maker.getPrice(totalorder); pricenoise = MathUtil.gRand(noiselevel, randnum); newprice = newprice + pricenoise; oldreturns = volatility; volatility = (newprice - price); valueadd = MathUtil.gRand(0.01, randnum); maker.updatePrice(newprice); totalorder = totalorder - makerorder; maker.updatePosition(totalorder); for(j = 0; j < N; j++) { value[j] = value[j] + valueadd; trader[j].updatePrice(newprice); trader[j].updateValue(value[j]); trader[j].updatePosition(orders[j]); trender[j].updatePrice(newprice); trender[j].updatePosition(trendorders[j]); if (trendorders[j] > 0){volume = volume + trendorders[j];} if (orders[j] > 0){volume = volume + orders[j];} } // end for j if (totalorder < 0){volume = volume - totalorder;} Format.printf("%6d ", i); maker.printoutWealth(); trader[0].printoutWealth(); trader[1].printoutWealth(); //Format.printf(" %10.6f", orders[1]); trender[0].printoutWealth(); //Format.printf(" %10.6f", trendorders[0]); trender[1].printoutWealth(); Format.printf(" %10.6f", trendorders[1]); trendprofits[0] = trender[0].getProfits(); trendprofits[1] = trender[1].getProfits(); valueprofits[0] = trader[0].getProfits(); valueprofits[1] = trader[1].getProfits(); makerprofits = maker.getProfits(); oldprice = price; price = newprice; Format.printf(" %10.6f", valueprofits[0]); Format.printf(" %10.6f", valueprofits[1]); Format.printf(" %10.6f", trendprofits[0]); Format.printf(" %10.6f", trendprofits[1]); Format.printf(" %10.6f", makerprofits); Format.printf(" %10.6f", price); Format.printf(" %10.6f ", value[0]); Format.printf(" %10.6f ", value[1]); Format.printf(" %10.6f ", volatility); Format.printf(" %10.6f ", oldreturns); Format.printf(" %10.6f ", oldprice); Format.printf(" %10.4f", volume); Format.printf(" %10.6f \n", mispricing); // Fourier Transform of volatility dc = dc + (1.0/totaltime)*volatility; misdc = misdc + (1.0/totaltime)*mispricing; dcval = dcval + (1.0/totaltime)*valueadd; volumedc = volumedc + (1.0/totaltime)*volume; for (j = 1; j <= fouriertop; j++) { inside = 2.0*pi*j*i/totaltime; b[j] = b[j] + (2.0/totaltime)*volatility*Math.cos(inside); a[j] = a[j] + (2.0/totaltime)*volatility*Math.sin(inside); mispricinga[j] = mispricinga[j] + (2.0/totaltime)*mispricing*Math.sin(inside); mispricingb[j] = mispricingb[j] + (2.0/totaltime)*mispricing*Math.cos(inside); aval[j] = aval[j] + (2.0/totaltime)*valueadd*Math.sin(inside); bval[j] = bval[j] + (2.0/totaltime)*valueadd*Math.cos(inside); pricenoisea[j] = pricenoisea[j] + (2.0/totaltime)*pricenoise*Math.sin(inside); pricenoiseb[j] = pricenoiseb[j] + (2.0/totaltime)*pricenoise*Math.cos(inside); volumea[j] = volumea[j] + (2.0/totaltime)*volume*Math.sin(inside); volumeb[j] = volumeb[j] + (2.0/totaltime)*volume*Math.cos(inside); } //end for j (Fourier) } //end for i // Power spectrum of Fourier Transform try{ FileOutputStream fout = new FileOutputStream("powerspec"); PrintStream powerout = new PrintStream(fout); FileOutputStream fout2 = new FileOutputStream("autocorr"); PrintStream autoout = new PrintStream(fout2); //corrdc = corrdc + dc*dc/totaltime; miscorrdc = miscorrdc + misdc*misdc/fouriertop; volumecorrdc = volumecorrdc + volumedc*volumedc/fouriertop; for (j=1; j <= fouriertop; j++) { powerspectrum[j] = a[j]*a[j] + b[j]*b[j]; valpow[j] = aval[j]*aval[j] + bval[j]*bval[j]; pricepow[j] = pricenoisea[j]*pricenoisea[j] + pricenoiseb[j]*pricenoiseb[j]; mispower[j] = mispricinga[j]*mispricinga[j] + mispricingb[j]*mispricingb[j]; volumepow[j] = volumea[j]*volumea[j] + volumeb[j]*volumeb[j]; corrdc = corrdc + (1.0/fouriertop)*powerspectrum[j]; miscorrdc = miscorrdc + (1.0/fouriertop)*mispower[j]; volumecorrdc = volumecorrdc + (1.0/fouriertop)*volumepow[j]; for (k=1; k <=fouriertop2; k++) {inside = -2.0*pi*k*j/totaltime; acorr[k] = acorr[k] + (2.0/totaltime)*powerspectrum[j]*Math.sin(inside); bcorr[k] = bcorr[k] + (2.0/totaltime)*powerspectrum[j]*Math.cos(inside); mispricingcorr[k] = mispricingcorr[k] + (2.0/fouriertop)*mispower[j]*Math.cos(inside); volumecorr[k] = volumecorr[k] + (2.0/fouriertop)*volumepow[j]*Math.cos(inside); } } corrdc = corrdc + dc*dc/fouriertop; // for (k=1; k <=fouriertop2; k++) // { bcorr[k] = bcorr[k] + (2.0/fouriertop)*dc*dc; // } for (j=1; j < fouriertop/15 ; j++) { smoothvalp[j] = 0.0; smoothretp[j] = 0.0; smoothpricepow[j] = 0.0; for (k = 1; k < 15; k++) { smoothvalp[j] = smoothvalp[j] + valpow[15*j + k]; smoothretp[j] = smoothretp[j] + powerspectrum[15*j + k]; smoothpricepow[j] = smoothpricepow[j] + pricepow[15*j + k]; } pricefilter[j] = smoothretp[j]/smoothpricepow[j]; filter[j] = smoothretp[j]/smoothvalp[j]; filteradd = filteradd + pricefilter[j]/fouriertop; smoothretp[j] /= 15.0; smoothpricepow[j] /= 15.0; smoothvalp[j] /= 15.0; } // end j (smoothing) for (j=1; j < fouriertop; j++) { freqindex = 12.0*j/totaltime; periodindex = 1.0/freqindex; powerout.println(" " + j + " " + powerspectrum[j] + " " + a[j] + " " + b[j] + " " + mispower[j] + " " + valpow[j] + " " + smoothretp[j] + " " + smoothvalp[j] + " " + filter[j] + " " + pricefilter[j] + " " + smoothpricepow[j] + " " + freqindex + " " + filteradd + " " + periodindex + " " + volumepow[j]); } autoout.println( " 0 " + corrdc*corrdc + " 0.0 1.0 1.0 1.0 1.0 1.0"); corrcalc[0] = 1.0; corrcalc[1] = (1.0 - alpha)/(1.0-alpha*(1.0-beta)); for (j=1; j <= fouriertop2; j++) { acorr[j] = acorr[j]/corrdc; bcorr[j] = bcorr[j]/corrdc; mispricingcorr[j] = mispricingcorr[j]/miscorrdc; volumecorr[j] = volumecorr[j]/volumecorrdc; corrcalc[j+1] = (1.0 - alpha)*corrcalc[j] + alpha*(1.0 - beta)*corrcalc[j-1]; autopower[j] = acorr[j]*acorr[j] + bcorr[j]*bcorr[j]; autoout.println(" " + j + " " + autopower[j] + " " + acorr[j] + " " + bcorr[j] + " " + corrdc + " " + corrcalc[j] + " " + mispricingcorr[j] + " " + volumecorr[j]); } } catch (IOException e) { System.out.println("Error opening file: " + e); System.exit(1); } } //end main } //end MarketSimMathUtil.java0100640000203700000250000000131707243273402013346 0ustar pmelbysfiguestimport java.lang.*; import java.util.*; class MathUtil { public static double gRand(double w, Random randnum) { int i = 0; double x = 0; double y; double arg; double yarg; while (i ==0) { x = 6*(randnum.nextDouble()-0.5); y = randnum.nextDouble(); arg = -1.0*x*x/2.0; yarg = Math.pow(Math.E, arg); if(y <= yarg) {i = 1;} } //end while x = w*x; return x; } public static double tanh(double x) { double exppos; double expneg; double hyptan; exppos = Math.exp(x); expneg = Math.exp(-1.0*x); hyptan = (exppos - expneg)/(exppos + expneg); return hyptan; } } // end class MathUtilPosition.java0100640000203700000250000000146707243273405013434 0ustar pmelbysfiguestimport java.util.*; import java.lang.*; import corejava.*; class Position { public Position(double x1, double x2, double m) { holdings = x1; oldholdings = x2; money = m; money = Math.exp(money); } public double getHoldings() { return holdings; } public double getMoney() { return money; } public void updatePosition(double order, double price) { money = money - (order)*Math.exp(price); oldholdings = holdings; holdings = holdings + order; } public void printWealth(double price) { double wealth; wealth = holdings*Math.exp(price) + money; Format.printf(" %10.2f ", wealth); Format.printf(" %10.2f ", holdings); Format.printf(" %10.2f ", money); } private double holdings; private double oldholdings; private double money; }TrendFollower.java0100640000203700000250000000340307243273413014405 0ustar pmelbysfiguestimport corejava.*; class TrendFollower { public TrendFollower(Position x, int d, double p, double c, double l) { equity = x; delay = d; newp = p; coeff = c; margin = l; int i; double price[] = new double[1000]; // for (i=0; i < 1000; i++){price[i] = newp;} } // end ValueInvestor init public void setPrice(double p) { for (i=0; i < 1000; i++){price[i] = p;} } public void updatePrice(double newprice) { for (i=0; i <= delay; i++) { price[i] = price[i+1]; } price[delay] = newprice; } public void updateMargin(double newmargin) { margin = newmargin; } public void updatePosition(double order) { double priceindex; priceindex = price[delay]; equity.updatePosition(order, priceindex); } public void printoutWealth() { equity.printWealth(price[delay]); Format.printf(" %10.6f", price[delay]); Format.printf(" %10.6f", price[0]); } public double getProfits() { double profits; double holdings; double money; double wealth; double initmoney = Math.exp(8.0); holdings = equity.getHoldings(); money = equity.getMoney(); wealth = money + Math.exp(price[delay])*holdings; profits = (wealth - initmoney)/initmoney; return profits; } public double placeOrder() { double order; double wants; double realequity; realequity = equity.getHoldings(); wants = coeff*(price[delay] - price[0]); order = wants - realequity; return order; } // end placeOrder private Position equity; private int delay; private double newp; private double coeff; private double margin; private double[] price = new double[1000]; private int i; } // end ValueInvestor class ValueInvestor.java0100640000203700000250000000306607243273414014433 0ustar pmelbysfiguestclass ValueInvestor { public ValueInvestor(Position x, double v, double p, double c, double l) { equity = x; value = v; price = p; coeff = c; margin = l; } // end ValueInvestor init public void updatePrice(double newprice) { price = newprice; } public void updateValue(double newvalue) { value = newvalue; } public void updateMargin(double newmargin) { margin = newmargin; } public void updatePosition(double order) { equity.updatePosition(order, price); } public void printoutWealth() { equity.printWealth(price); } public double getProfits() { double profits; double holdings; double money; double wealthy; double initmoney = Math.exp(8.0); holdings = equity.getHoldings(); money = equity.getMoney(); wealthy = money + Math.exp(price)*holdings; profits = ( wealthy - initmoney)/initmoney; return profits; } public double placeOrder() { double order; double wants; double realequity = equity.getHoldings(); double w; double money = equity.getMoney(); w = money + Math.exp(price)*realequity; w = w/price; wants = coeff*(value - price); //wants = coeff*MathUtil.tanh(2.0*(value-price)); //wants = w*MathUtil.tanh(2.0*(value-price)); order = wants - realequity; return order; } // end placeOrder private Position equity; private double value; private double price; private double coeff; private double margin; private double initequity; } // end ValueInvestor class corejava/0040750000203700000250000000000007243273447012557 5ustar pmelbysfiguestcorejava/Assertion.java0100640000203700000250000000574007243273447015375 0ustar pmelbysfiguestpackage corejava; /** A class for assertion checking @version 1.00 10 Oct 1998 @author Cay Horstmann */ public class Assertion { /** Check an assertion @param b the condition to check @param s a string describing the check @throws Assertion.Failure if condition not true */ public static void check(boolean b, String s) { if (doCheck && !b) throw new Failure(s); } /** Check an assertion @param b the condition to check @throws Assertion.Failure if condition not true */ public static void check(boolean b) { if (doCheck && !b) throw new Failure(); } /** Check an assertion @param obj an object to check @param s a string describing the check @throws Assertion.Failure if object is null */ public static void check(Object obj, String s) { if (doCheck && obj == null) throw new Failure(s); } /** Check an assertion @param obj an object to check @throws Assertion.Failure if object is null */ public static void check(Object obj) { if (doCheck && obj == null) throw new Failure(); } /** Check an assertion @param x a number @param s a string describing the check @throws Assertion.Failure if number is 0 */ public static void check(double x, String s) { if (doCheck && x == 0) throw new Failure(s); } /** Check an assertion @param x a number @throws Assertion.Failure if number is 0 */ public static void check(double x) { if (doCheck && x == 0) throw new Failure(); } /** Check an assertion @param x a number @param s a string describing the check @throws Assertion.Failure if number is 0 */ public static void check(long x, String s) { if (doCheck && x == 0) throw new Failure(s); } /** Check an assertion @param x a number @throws Assertion.Failure if number is 0 */ public static void check(long x) { if (doCheck && x == 0) throw new Failure(); } /** Turn checking on or off @param c true to turn checking on, false to turn checking off */ public static void setCheck(boolean c) { doCheck = c; } private static boolean doCheck = true; /** test stub */ public static void main(String[] args) { Assertion.check(args); Assertion.check(args.length, "No command line arguments"); } /** A class for reporting assertion failures */ public static class Failure extends RuntimeException { public Failure() { super("Assertion failed"); } /** @param gripe a description of the reason for the failure */ public Failure(String gripe) { super(gripe); } } } corejava/Console.java0100640000203700000250000000512207243273447015022 0ustar pmelbysfiguestpackage corejava; /** An easy interface to read numbers and strings from standard input @version 1.10 10 Mar 1997 @author Cay Horstmann */ public class Console { /** print a prompt on the console but don't print a newline @param prompt the prompt string to display */ public static void printPrompt(String prompt) { System.out.print(prompt + " "); System.out.flush(); } /** read a string from the console. The string is terminated by a newline @return the input string (without the newline) */ public static String readLine() { int ch; String r = ""; boolean done = false; while (!done) { try { ch = System.in.read(); if (ch < 0 || (char)ch == '\n') done = true; else if ((char)ch != '\r') // weird--it used to do \r\n translation r = r + (char) ch; } catch(java.io.IOException e) { done = true; } } return r; } /** read a string from the console. The string is terminated by a newline @param prompt the prompt string to display @return the input string (without the newline) */ public static String readLine(String prompt) { printPrompt(prompt); return readLine(); } /** read an integer from the console. The input is terminated by a newline @param prompt the prompt string to display @return the input value as an int @exception NumberFormatException if bad input */ public static int readInt(String prompt) { while(true) { printPrompt(prompt); try { return Integer.valueOf (readLine().trim()).intValue(); } catch(NumberFormatException e) { System.out.println ("Not an integer. Please try again!"); } } } /** read a floating point number from the console. The input is terminated by a newline @param prompt the prompt string to display @return the input value as a double @exception NumberFormatException if bad input */ public static double readDouble(String prompt) { while(true) { printPrompt(prompt); try { return Double.parseDouble(readLine().trim()); } catch(NumberFormatException e) { System.out.println ("Not a floating point number. Please try again!"); } } } } corejava/Day.java0100640000203700000250000001373707243273447014150 0ustar pmelbysfiguestpackage corejava; import java.util.*; import java.io.*; /** Stores dates and perform date arithmetic. This is another date class, but more convenient that java.util.Date or java.util.Calendar @version 1.20 5 Oct 1998 @author Cay Horstmann */ public class Day implements Cloneable, Serializable { /** Constructs today's date */ public Day() { GregorianCalendar todaysDate = new GregorianCalendar(); year = todaysDate.get(Calendar.YEAR); month = todaysDate.get(Calendar.MONTH) + 1; day = todaysDate.get(Calendar.DAY_OF_MONTH); } /** Constructs a specific date @param yyyy year (full year, e.g., 1996, not starting from 1900) @param m month @param d day @exception IllegalArgumentException if yyyy m d not a valid date */ public Day(int yyyy, int m, int d) { year = yyyy; month = m; day = d; if (!isValid()) throw new IllegalArgumentException(); } /** Advances this day by n days. For example. d.advance(30) adds thirdy days to d @param n the number of days by which to change this day (can be < 0) */ public void advance(int n) { fromJulian(toJulian() + n); } /** Gets the day of the month @return the day of the month (1...31) */ public int getDay() { return day; } /** Gets the month @return the month (1...12) */ public int getMonth() { return month; } /** Gets the year @return the year (counting from 0, not from 1900) */ public int getYear() { return year; } /** Gets the weekday @return the weekday (address@hidden Day#SUNDAY}, ..., address@hidden Day#SATURDAY}) */ public int weekday() { return (toJulian() + 1) % 7 + 1; } /** The number of days between this and day parameter @param b any date @return the number of days between this and day parameter and b (> 0 if this day comes after b) */ public int daysBetween(Day b) { return toJulian() - b.toJulian(); } /** A string representation of the day @return a string representation of the day */ public String toString() { return "Day[" + year + "," + month + "," + day + "]"; } /** Makes a bitwise copy of a Day object @return a bitwise copy of a Day object */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable return null; } } /** Compares this Day against another object @param obj another object @return true if the other object is identical to this Day object */ public boolean equals(Object obj) { if (!getClass().equals(obj.getClass())) return false; Day b = (Day)obj; return day == b.day && month == b.month && year == b.year; } /** Computes the number of days between two dates @return true iff this is a valid date */ private boolean isValid() { Day t = new Day(); t.fromJulian(this.toJulian()); return t.day == day && t.month == month && t.year == year; } /** @return The Julian day number that begins at noon of this day Positive year signifies A.D., negative year B.C. Remember that the year after 1 B.C. was 1 A.D. A convenient reference point is that May 23, 1968 noon is Julian day 2440000. Julian day 0 is a Monday. This algorithm is from Press et al., Numerical Recipes in C, 2nd ed., Cambridge University Press 1992 */ private int toJulian() { int jy = year; if (year < 0) jy++; int jm = month; if (month > 2) jm++; else { jy--; jm += 13; } int jul = (int) (java.lang.Math.floor(365.25 * jy) + java.lang.Math.floor(30.6001*jm) + day + 1720995.0); int IGREG = 15 + 31*(10+12*1582); // Gregorian Calendar adopted Oct. 15, 1582 if (day + 31 * (month + 12 * year) >= IGREG) // change over to Gregorian calendar { int ja = (int)(0.01 * jy); jul += 2 - ja + (int)(0.25 * ja); } return jul; } /** Converts a Julian day to a calendar date This algorithm is from Press et al., Numerical Recipes in C, 2nd ed., Cambridge University Press 1992 @param j the Julian date */ private void fromJulian(int j) { int ja = j; int JGREG = 2299161; /* the Julian date of the adoption of the Gregorian calendar */ if (j >= JGREG) /* cross-over to Gregorian Calendar produces this correction */ { int jalpha = (int)(((float)(j - 1867216) - 0.25) / 36524.25); ja += 1 + jalpha - (int)(0.25 * jalpha); } int jb = ja + 1524; int jc = (int)(6680.0 + ((float)(jb-2439870) - 122.1) /365.25); int jd = (int)(365 * jc + (0.25 * jc)); int je = (int)((jb - jd)/30.6001); day = jb - jd - (int)(30.6001 * je); month = je - 1; if (month > 12) month -= 12; year = jc - 4715; if (month > 2) --year; if (year <= 0) --year; } public static int SUNDAY = 1; public static int MONDAY = 2; public static int TUESDAY = 3; public static int WEDNESDAY = 4; public static int THURSDAY = 5; public static int FRIDAY = 6; public static int SATURDAY = 7; /** @serial */ private int day; /** @serial */ private int month; /** @serial */ private int year; } corejava/Format.class0100640000203700000250000002035707243273447015043 0ustar pmelbysfiguestÊþº¾-iÑÊþÒóôõö÷øùúûü !"address@hidden)*+,-./01 H¢ K¢ M£ E¤ M¤ E¥ M¦ M§ M¨ M© Eª L« E¬ E­ E® E¯ E° E± E² E³ E´ Gµ E¶ E· L¸ N¹ Eº E» E¼ J½ E¾ E¿ FÀ EÁ E Eà EÄ EÅ EÆ EÇ EÈ EÉ LÊ LË MÌ LÍ LÎ LÏ EÐ address@hidden@address@hidden@address@hidden|í‘hs>éàü¯“€üF/)Äî±Uåÿÿÿÿ?óÀÊBŒ+€Cà ýÕ ýß ýë    ×  Þ  ã  ê  è Ü ä $Ú %Ú &þ 'Ö 'Ú 'Ý 'â 'é (Ø 2 3 4Ó 6 7é 8î 9 :Û ; < =ë >ì >í >ï >ð >ñ ?Ù B C Dá EÝ Eà FÔ JÖ Jâ Jå N ()I()Ljava/lang/String;()V(C)Ljava/lang/String;(C)Ljava/lang/StringBuffer;(C)Z(CI)Ljava/lang/String;(D)Ljava/lang/String;(DD)D(I)C(I)Ljava/lang/String;(I)Ljava/lang/StringBuffer;(I)V(II)Ljava/lang/String;'(ILjava/lang/String;)Ljava/lang/String;(J)Ljava/lang/String;(J)Ljava/lang/StringBuffer;)(JIILjava/lang/String;)Ljava/lang/String;&(Ljava/lang/Object;)Ljava/lang/String;(Ljava/lang/String;)D(Ljava/lang/String;)I(Ljava/lang/String;)J&(Ljava/lang/String;)Ljava/lang/String;,(Ljava/lang/String;)Ljava/lang/StringBuffer;(Ljava/lang/String;)V(Ljava/lang/String;C)V(Ljava/lang/String;D)V(Ljava/lang/String;I)J(Ljava/lang/String;I)V(Ljava/lang/String;J)V'(Ljava/lang/String;Ljava/lang/String;)V([Ljava/lang/String;)V+-.0000012345670123456789ABCDEF0123456789abcdef0X0xCCodeE Format.javaHelloILineNumberTableLjava/io/PrintStream;Ljava/lang/String; SourceFileZ alternateappendatofatoiatolcharAtconvertcorejava/Format d = |% 020d|  d = |%#020o|  d = |%#20o|  d = |%#20x|  d = |%+20d|  d = |%-20d|  d = |%020X|  d = |%020d|  d = |%020o| d = |%20.12o|  d = |%20.8d|  d = |%20.8x|  d = |%20X|  d = |%20d|  d = |%X|  d = |%d|  d = |%o|  d = |%x| e exp_format fixed_formatfmtformat isWhitespacejava/io/PrintStreamjava/lang/Character"java/lang/IllegalArgumentExceptionjava/lang/Longjava/lang/Mathjava/lang/Objectjava/lang/Stringjava/lang/StringBufferjava/lang/Systemleading_zeroes left_alignlengthmainoutpad parseLongpostpowpre precisionprintprintfrepeat s = |%-20c|  s = |%-20s|  show_plus show_spacesign substringtoString u = |%20e|  u = |%20f|  u = |%g| valueOf w = |%20.5e|  w = |%20.5f|  w = |%g| width x = |% .5e|  x = |% .5f| x = |% 020.5e| x = |% 020.5f| x = |%+020.5e| x = |%+020.5f| x = |%+20.5e| x = |%+20.5f| x = |%020.5e| x = |%020.5f|  x = |%e|  x = |%f|  x = |%g| y = |%#+20.5e| y = |%#+20.5f|  y = |%#.2g| y = |%-+20.5e| y = |%-+20.5f|  y = |%.2g|  z = |%20.5f|  z = |%g| |%6.0f| |%6.2e| |%6.2f| |%6.2g| |%i| !EK N<;92B C3&þýëÿB"*·P*µ*µn*µm*µk*µe*µv*µT*µw*µf* µ^=+¶g>66§~¡ 6§o+¶Z% Fd¢6+`¶Z% #*»MY*´m¸~·S%¶U¶{µm„§/6§)»HY·O¿*»MY*´m¸~·S+¶Z¶U¶{µm„™ÿƒ§w¡ 6§h+¶Z   *µw§U+¶Z-  *µf§B+¶Z+  *µv§/+¶Z0  *µe§+¶Z#  *µT§ 6„ÿ„Ÿÿ‰§\¡ 6§P+¶Z0¡)+¶Z9£**´ h+¶Z`0dµ„§+¶Z. 6*µn„§6Ÿÿ¤§C¡ 6§7+¶Z0¡)+¶Z9£**´n h+¶Z`0dµn„§6Ÿÿ½ ¡ 6§ *+¶Zµ^„¢*+¶zµk±C56 789:;$<)=.>3?9A;address@hidden@YFcIdUekf€gƒe†i‘j”k™lœiŸo¢c¨q«r·sÍtâuåsèxëqñz÷{| }€!5  æÿƒ û<=J996 §„*¶g¢*¶Z¸dšÿí*¶g¢*¶Z-  =„§¯*¶g¢§*¶Z+ „§—*¶Z6  0¡= 9£6 š)Œk ‡cŽgJ§i  cŒo9) 0d‡kcJ§L .  š 6 §:‡)k¯ eŸ  E "*`¶y ¸jˆ…7 ‡)kŒ Š¸lk¯‡)k¯„*¶g¡ÿg‡)k¯vö÷øù ú ûý(þBÿWZaot‚…‹“Ÿ¢ © ´ ¹Ç×æëîö  çÿ*¸Yˆ¬  èÿšj<§„*¶g¢*¶Z¸dšÿí*¶g¢C*¶Z0 9`*¶g¢(*`¶ZxŸ*`¶ZX *`¶y¸j­*¸j­* ¸j­ÍÏÐ-ÑOÒ\ÓcÕ äÿk; ”š°:§%»MY…ˆ¶Z¸|·S¶X¶{:}? ”šÿÛ°Ð Ñ ÒÓ.Ô2Ò8Ö$Úÿà SN6'99'—™?§„Œo9Œo9Œ—ÿ秄ÿŒk9Œk9˜›ÿé*´^gŸ *´^G ü¡*´n¢ *'·]°'kH»MY-¸~·S*'·]¶X¶{N*´^eŸ *´^g »MY-¸~·S"¶X¶{N§»MY-¸~·S¶X¶{N: ›0»MY-¸~·S¶X¶{N»MY ¸~·S¶V¶{: §.»MY-¸~·S¶X¶{N»MY ¸~·St¶V¶{: »MY-¸~·S  ¶gd ¶g¶z¶X¶{°^  1N p!v#{$’&¤'¸&»)Ï+Ó,Ø-ì.,1205%ÚÿÛg*´^GŸ *´^g  *´T™§>' —ž *'·\°*´nš%»MY'ˆc¸}·S™§¶X¶{°'7'Šg9—œ ˜œ *'·\°9: 6 §$Œk9»MY ¸~·S¶X¶{: „  *´n£  ˜žÿÐkˆc7  Š—› 7  a7»MY ¸~·S ¶W¶{:»MY·S¶g*´nd¶g¶z¶X¶{:™C¶gd6§„ÿ›¶Z0ŸÿZ. „ÿ`¶z:»MY¸}·S¶X¶{°böõù-ú4ûVýZþaÿux|‚Š µÁÓ é  2FR'address@hidden|M*,·i°c dfg'Úÿ¯o*´nœ *µn6'˜œ 'wH6*´^f  *'·]N§8*´^eŸ*´^EŸ*´^gŸ *´^G  *'·\N§ »HY·O¿**-·x·i°. " #$%%&+%.'R(X'[)c+'ÝÿN*…A*´^oŸ*´^xŸ *´^X  šA* ¶b°678$9'âÿï‹6*´^dŸ *´^i # ”œ¸}¶yN6§X¸}N6§M*´^o  ¸[N§7*´^x  ¸[N§!*´^X  ¸[N§ »HY·O¿**-·x·i°REFGH$I'G*L/M2F5P>QHPKRTS^RaTjUtTwVX'éÿ[3*´^sŸ »HY·O¿*´n›*´n+¶g¢ +*´n¶zL*+·i°r st#u-v 5òÿ‰ œH’J˜9Š9–9 6 6'¸q& ¸q,'¸q)¸q4'¸q2'¸q0'¸q.'¸q9)¸q<)¸q>¸q5'¸q% ¸q+'¸q(¸q3'¸q1'¸q/'¸q-'¸q8)¸q;)¸q7'¸q?¸q*¸q' ¸q=)¸q:)¸q ¸r ¸r ¸r ¸r ¸r ¸r ¸r! ¸r ¸r ¸r ¸r ¸r address@hidden ‚ƒ„…!†(‡.ˆ5‰;ŠA‹GŒMSŽY`‘f’m“s”z•€–†—Œ˜’™˜šžœ¤«ž²Ÿ¹ ¿¡Å£Ì¤Ó¥Ú¦á§è¨ï©öªý«¬ ­®¯ °'±.²5³<µC¶JºR¼X½^¿fÀnÂvÄyÅ€~7éÿxX *´+¶gd¸uM*´f™$»MY*´m¸~·S+¶X,¶X*´k¶X¶{°»MY*´m¸~·S,¶X+¶X*´k¶X¶{°ÚÛ7Ü 8îÿLä=> 7§„*¶g¢*¶Z¸dšÿí*¶g¢*¶Z-  >„§Ÿ*¶g¢—*¶Z+ „§‡*¶Z60¡0`¢…i…a‚e7§[A¡%A` d¢…i…a„e€a7§2a¡%a` d¢…i…a†e€a7§ …i­„*¶g¡ÿw…i­VÙÚÛÝ Þ:ßOàRáYâiãxâ{äŽå¡ä¤æ·çÊæÍéÓêÖàÞì >ìÿ/²h»EY*·R¶_¶o± ¬« >íÿ/²h»EY*·R'¶`¶o± ‹Š >ïÿ/²h»EY*·R¶a¶o± –• >ðÿ/²h»EY*·R¶b¶o± ¡  >ñÿ/²h»EY*·R+¶c¶o± ·¶ ?ÙÿL(°»MY·QM>§ ,¶UW„¡ÿõ,¶{°ÉÊË#ÌDáÿCïNœ N§qž*´v™ N§`*´w™YN§S*´^o !*´T™,¶gž,¶Z0Ÿ N§,*´^x *´T™  N§*´^X  *´T™ N6*´e™ *´6§=*´^dŸ'*´^iŸ*´^xŸ*´^XŸ *´^o *´nž *´n6»MY-¸~·S0-¶gd,¶gd¸u¶X,¶X¶{°Bàá âãä(â+çRèhé{ë~ì…í‹ìŽî»ïÈñcorejava/Format.java0100640000203700000250000004235507243273447014661 0ustar pmelbysfiguestpackage corejava; import java.io.*; /** A class for formatting numbers that follows printf conventions. Also implements C-like atoi and atof functions @version 1.20 25 Mar 1998 @author Cay Horstmann */ public class Format { /** Formats the number following printf conventions. Main limitation: Can only handle one format parameter at a time Use multiple Format objects to format more than one number @param s the format string following printf conventions The string has a prefix, a format code and a suffix. The prefix and suffix become part of the formatted output. The format code directs the formatting of the (single) parameter to be formatted. The code has the following structure @exception IllegalArgumentException if bad format */ public Format(String s) { width = 0; precision = -1; pre = ""; post = ""; leading_zeroes = false; show_plus = false; alternate = false; show_space = false; left_align = false; fmt = ' '; int state = 0; int length = s.length(); int parse_state = 0; // 0 = prefix, 1 = flags, 2 = width, 3 = precision, // 4 = format, 5 = end int i = 0; while (parse_state == 0) { if (i >= length) parse_state = 5; else if (s.charAt(i) == '%') { if (i < length - 1) { if (s.charAt(i + 1) == '%') { pre = pre + '%'; i++; } else parse_state = 1; } else throw new java.lang.IllegalArgumentException(); } else pre = pre + s.charAt(i); i++; } while (parse_state == 1) { if (i >= length) parse_state = 5; else if (s.charAt(i) == ' ') show_space = true; else if (s.charAt(i) == '-') left_align = true; else if (s.charAt(i) == '+') show_plus = true; else if (s.charAt(i) == '0') leading_zeroes = true; else if (s.charAt(i) == '#') alternate = true; else { parse_state = 2; i--; } i++; } while (parse_state == 2) { if (i >= length) parse_state = 5; else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') { width = width * 10 + s.charAt(i) - '0'; i++; } else if (s.charAt(i) == '.') { parse_state = 3; precision = 0; i++; } else parse_state = 4; } while (parse_state == 3) { if (i >= length) parse_state = 5; else if ('0' <= s.charAt(i) && s.charAt(i) <= '9') { precision = precision * 10 + s.charAt(i) - '0'; i++; } else parse_state = 4; } if (parse_state == 4) { if (i >= length) parse_state = 5; else fmt = s.charAt(i); i++; } if (i < length) post = s.substring(i, length); } /** prints a formatted number following printf conventions @param fmt the format string @param x the double to print */ public static void printf(String fmt, double x) { System.out.print(new Format(fmt).format(x)); } /** prints a formatted number following printf conventions @param fmt the format string @param x the int to print */ public static void printf(String fmt, int x) { System.out.print(new Format(fmt).format(x)); } /** prints a formatted number following printf conventions @param fmt the format string @param x the long to print */ public static void printf(String fmt, long x) { System.out.print(new Format(fmt).format(x)); } /** prints a formatted number following printf conventions @param fmt the format string @param x the character to print */ public static void printf(String fmt, char x) { System.out.print(new Format(fmt).format(x)); } /** prints a formatted number following printf conventions @param fmt the format string @param x a string to print */ public static void printf(String fmt, String x) { System.out.print(new Format(fmt).format(x)); } /** Converts a string of digits (decimal, octal or hex) to an integer @param s a string @return the numeric value of the prefix of s representing a base 10 integer */ public static int atoi(String s) { return (int)atol(s); } /** Converts a string of digits (decimal, octal or hex) to a long integer @param s a string @return the numeric value of the prefix of s representing a base 10 integer */ public static long atol(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; if (i < s.length() && s.charAt(i) == '0') { if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X')) return parseLong(s.substring(i + 2), 16); else return parseLong(s, 8); } else return parseLong(s, 10); } private static long parseLong(String s, int base) { int i = 0; int sign = 1; long r = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; } else if (i < s.length() && s.charAt(i) == '+') { i++; } while (i < s.length()) { char ch = s.charAt(i); if ('0' <= ch && ch < '0' + base) r = r * base + ch - '0'; else if ('A' <= ch && ch < 'A' + base - 10) r = r * base + ch - 'A' + 10 ; else if ('a' <= ch && ch < 'a' + base - 10) r = r * base + ch - 'a' + 10 ; else return r * sign; i++; } return r * sign; } /** Converts a string of digits to a double @param s a string */ public static double atof(String s) { int i = 0; int sign = 1; double r = 0; // integer part double f = 0; // fractional part double p = 1; // exponent of fractional part int state = 0; // 0 = int part, 1 = frac part while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; } else if (i < s.length() && s.charAt(i) == '+') { i++; } while (i < s.length()) { char ch = s.charAt(i); if ('0' <= ch && ch <= '9') { if (state == 0) r = r * 10 + ch - '0'; else if (state == 1) { p = p / 10; r = r + p * (ch - '0'); } } else if (ch == '.') { if (state == 0) state = 1; else return sign * r; } else if (ch == 'e' || ch == 'E') { long e = (int)parseLong(s.substring(i + 1), 10); return sign * r * Math.pow(10, e); } else return sign * r; i++; } return sign * r; } /** Formats a double into a string (like sprintf in C) @param x the number to format @return the formatted string @exception IllegalArgumentException if bad argument */ public String format(double x) { String r; if (precision < 0) precision = 6; int s = 1; if (x < 0) { x = -x; s = -1; } if (fmt == 'f') r = fixed_format(x); else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G') r = exp_format(x); else throw new java.lang.IllegalArgumentException(); return pad(sign(s, r)); } /** Formats an integer into a string (like sprintf in C) @param x the number to format @return the formatted string */ public String format(int x) { long lx = x; if (fmt == 'o' || fmt == 'x' || fmt == 'X') lx &= 0xFFFFFFFFL; return format(lx); } /** Formats a long integer into a string (like sprintf in C) @param x the number to format @return the formatted string */ public String format(long x) { String r; int s = 0; if (fmt == 'd' || fmt == 'i') { if (x < 0) { r = ("" + x).substring(1); s = -1; } else { r = "" + x; s = 1; } } else if (fmt == 'o') r = convert(x, 3, 7, "01234567"); else if (fmt == 'x') r = convert(x, 4, 15, "0123456789abcdef"); else if (fmt == 'X') r = convert(x, 4, 15, "0123456789ABCDEF"); else throw new java.lang.IllegalArgumentException(); return pad(sign(s, r)); } /** Formats a character into a string (like sprintf in C) @param x the value to format @return the formatted string */ public String format(char c) { if (fmt != 'c') throw new java.lang.IllegalArgumentException(); String r = "" + c; return pad(r); } /** Formats a string into a larger string (like sprintf in C) @param x the value to format @return the formatted string */ public String format(String s) { if (fmt != 's') throw new java.lang.IllegalArgumentException(); if (precision >= 0 && precision < s.length()) s = s.substring(0, precision); return pad(s); } /** a test stub for the format class */ public static void main(String[] a) { double x = 1.23456789012; double y = 123; double z = 1.2345e30; double w = 1.02; double u = 1.234e-5; int d = 0xCAFE; Format.printf("x = |%f|\n", x); Format.printf("u = |%20f|\n", u); Format.printf("x = |% .5f|\n", x); Format.printf("w = |%20.5f|\n", w); Format.printf("x = |%020.5f|\n", x); Format.printf("x = |%+20.5f|\n", x); Format.printf("x = |%+020.5f|\n", x); Format.printf("x = |% 020.5f|\n", x); Format.printf("y = |%#+20.5f|\n", y); Format.printf("y = |%-+20.5f|\n", y); Format.printf("z = |%20.5f|\n", z); Format.printf("x = |%e|\n", x); Format.printf("u = |%20e|\n", u); Format.printf("x = |% .5e|\n", x); Format.printf("w = |%20.5e|\n", w); Format.printf("x = |%020.5e|\n", x); Format.printf("x = |%+20.5e|\n", x); Format.printf("x = |%+020.5e|\n", x); Format.printf("x = |% 020.5e|\n", x); Format.printf("y = |%#+20.5e|\n", y); Format.printf("y = |%-+20.5e|\n", y); Format.printf("x = |%g|\n", x); Format.printf("z = |%g|\n", z); Format.printf("w = |%g|\n", w); Format.printf("u = |%g|\n", u); Format.printf("y = |%.2g|\n", y); Format.printf("y = |%#.2g|\n", y); Format.printf("d = |%d|\n", d); Format.printf("d = |%20d|\n", d); Format.printf("d = |%020d|\n", d); Format.printf("d = |%+20d|\n", d); Format.printf("d = |% 020d|\n", d); Format.printf("d = |%-20d|\n", d); Format.printf("d = |%20.8d|\n", d); Format.printf("d = |%x|\n", d); Format.printf("d = |%20X|\n", d); Format.printf("d = |%#20x|\n", d); Format.printf("d = |%020X|\n", d); Format.printf("d = |%20.8x|\n", d); Format.printf("d = |%o|\n", d); Format.printf("d = |%020o|\n", d); Format.printf("d = |%#20o|\n", d); Format.printf("d = |%#020o|\n", d); Format.printf("d = |%20.12o|\n", d); Format.printf("s = |%-20s|\n", "Hello"); Format.printf("s = |%-20c|\n", '!'); // regression test to confirm fix of reported bugs Format.printf("|%i|\n", Long.MIN_VALUE); Format.printf("|%6.2e|\n", 0.0); Format.printf("|%6.2g|\n", 0.0); Format.printf("|%6.2f|\n", 9.99); Format.printf("|%6.2f|\n", 9.999); Format.printf("|%6.0f|\n", 9.999); d = -1; Format.printf("d = |%X|\n", d); } private static String repeat(char c, int n) { if (n <= 0) return ""; StringBuffer s = new StringBuffer(n); for (int i = 0; i < n; i++) s.append(c); return s.toString(); } private static String convert(long x, int n, int m, String d) { if (x == 0) return "0"; String r = ""; while (x != 0) { r = d.charAt((int)(x & m)) + r; x = x >>> n; } return r; } private String pad(String r) { String p = repeat(' ', width - r.length()); if (left_align) return pre + r + p + post; else return pre + p + r + post; } private String sign(int s, String r) { String p = ""; if (s < 0) p = "-"; else if (s > 0) { if (show_plus) p = "+"; else if (show_space) p = " "; } else { if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0"; else if (fmt == 'x' && alternate) p = "0x"; else if (fmt == 'X' && alternate) p = "0X"; } int w = 0; if (leading_zeroes) w = width; else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') && precision > 0) w = precision; return p + repeat('0', w - p.length() - r.length()) + r; } private String fixed_format(double d) { boolean removeTrailing = (fmt == 'G' || fmt == 'g') && !alternate; // remove trailing zeroes and decimal point if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d); if (precision == 0) return (long)(d + 0.5) + (removeTrailing ? "" : "."); long whole = (long)d; double fr = d - whole; // fractional part if (fr >= 1 || fr < 0) return exp_format(d); double factor = 1; String leading_zeroes = ""; for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) { factor *= 10; leading_zeroes = leading_zeroes + "0"; } long l = (long) (factor * fr + 0.5); if (l >= factor) { l = 0; whole++; } // CSH 10-25-97 String z = leading_zeroes + l; z = "." + z.substring(z.length() - precision, z.length()); if (removeTrailing) { int t = z.length() - 1; while (t >= 0 && z.charAt(t) == '0') t--; if (t >= 0 && z.charAt(t) == '.') t--; z = z.substring(0, t + 1); } return whole + z; } private String exp_format(double d) { String f = ""; int e = 0; double dd = d; double factor = 1; if (d != 0) { while (dd > 10) { e++; factor /= 10; dd = dd / 10; } while (dd < 1) { e--; factor *= 10; dd = dd * 10; } } if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) return fixed_format(d); d = d * factor; f = f + fixed_format(d); if (fmt == 'e' || fmt == 'g') f = f + "e"; else f = f + "E"; String p = "000"; if (e >= 0) { f = f + "+"; p = p + e; } else { f = f + "-"; p = p + (-e); } return f + p.substring(p.length() - 3, p.length()); } private int width; private int precision; private String pre; private String post; private boolean leading_zeroes; private boolean show_plus; private boolean alternate; private boolean show_space; private boolean left_align; private char fmt; // one of cdeEfgGiosxXos }corejava/RandomIntGenerator.java0100640000203700000250000000334707243273447017171 0ustar pmelbysfiguestpackage corejava; /** An improved random number generator based on Algorithm B in Knuth Vol 2 p32. Gives a set of random integers that does not exhibit as much correlation as the method used by the Java random number generator. @version 1.01 15 Feb 1996 @author Cay Horstmann */ public class RandomIntGenerator { /** Constructs an object that generates random integers in a given range @param l the lowest integer in the range @param h the highest integer in the range */ public RandomIntGenerator(int l, int h) { low = l; high = h; } /** Generates a random integer in a range of integers @return a random integer */ public int draw() { int r = low + (int)((high - low + 1) * nextRandom()); return r; } /** test stub for the class */ public static void main(String[] args) { RandomIntGenerator r1 = new RandomIntGenerator(1, 10); RandomIntGenerator r2 = new RandomIntGenerator(0, 1); int i; for (i = 1; i <= 100; i++) System.out.println(r1.draw() + " " + r2.draw()); } private static double nextRandom() { int pos = (int)(java.lang.Math.random() * BUFFER_SIZE); if (pos == BUFFER_SIZE) pos = BUFFER_SIZE - 1; double r = buffer[pos]; buffer[pos] = java.lang.Math.random(); return r; } private static final int BUFFER_SIZE = 101; private static double[] buffer = new double[BUFFER_SIZE]; static { int i; for (i = 0; i < BUFFER_SIZE; i++) buffer[i] = java.lang.Math.random(); } private int low; private int high; }