public void mouseDragged(MouseEvent evt) { Graphics g = canvas.getGraphics(); g.setColor(color); if (type == 0) { g.setXORMode(canvas.getBackground()); g.drawRect(start.x, start.y, end.x - start.x, end.y - start.y); end = evt.getPoint(); g.drawRect(start.x, start.y, end.x - start.x, end.y - start.y); } else if (type == 1) { int radius; g.setXORMode(canvas.getBackground()); radius = (int) Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)); g.drawOval(start.x - radius, start.y - radius, 2 * radius, 2 * radius); end = evt.getPoint(); radius = (int) Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)); g.drawOval(start.x - radius, start.y - radius, 2 * radius, 2 * radius); } else if (type == 2) { g.setXORMode(canvas.getBackground()); g.drawOval(start.x, start.y, end.x - start.x, end.y - start.y); end = evt.getPoint(); g.drawOval(start.x, start.y, end.x - start.x, end.y - start.y); } }
public void mouseReleased(MouseEvent evt) { Graphics g = canvas.getGraphics(); g.setColor(color); g.setPaintMode(); end = evt.getPoint(); if (type == 0) { g.drawRect(start.x, start.y, end.x - start.x, end.y - start.y); if (filled.getState() == true) g.fillRect(start.x, start.y, end.x - start.x, end.y - start.y); status.setText("2. Ecke des Rechtecks festgelegt"); } else if (type == 1) { int radius; radius = (int) Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)); g.drawOval(start.x - radius, start.y - radius, 2 * radius, 2 * radius); if (filled.getState() == true) g.fillOval(start.x - radius, start.y - radius, 2 * radius, 2 * radius); status.setText("Radius des Kreises festgelegt"); } else if (type == 2) { g.drawOval(start.x, start.y, end.x - start.x, end.y - start.y); if (filled.getState() == true) g.fillOval(start.x, start.y, end.x - start.x, end.y - start.y); status.setText("Radius der Ellipse festgelegt"); } }
private void spawnRandomers() { for (int i = 0; i < randomN; i++) { float x = (float) Math.random() * width; float y = (float) Math.random() * height; float r = (float) Math.sqrt( Math.pow(((Player) players.get(0)).getX() - x, 2) + Math.pow(((Player) players.get(0)).getY() - x, 2)); while (r < distanceLimit) { x = (float) Math.random() * width; y = (float) Math.random() * height; r = (float) Math.sqrt( Math.pow(((Player) players.get(0)).getX() - x, 2) + Math.pow(((Player) players.get(0)).getY() - y, 2)); } enemies.add(new EnemyTypes.Random(x, y, 0.5f, borders)); } spawnRandomersB = false; }
public double distanciaEuclidiana(int x1, int x2, int y1, int y2) { double a, b, c; a = Math.pow(x2 - x1, 2); b = Math.pow(y2 - y1, 2); c = Math.sqrt(a + b); return (c); }
public void paint(Graphics g) { level = level_in; left_width_factor = (float) Math.pow(2.0, -1 / left_alpha); right_width_factor = (float) Math.pow(2.0, -1 / right_alpha); left_height_factor = (float) Math.pow(2.0, -2 / (3 * left_alpha)); right_height_factor = (float) Math.pow(2.0, -2 / (3 * right_alpha)); x = (float) 600 / 2.0f; y = (float) 500 / 10.0f; x1 = x; y01 = y + height; drawbranch(g, width, (int) x, 500 - (int) y, (int) x1, 500 - (int) y01); turtle_r = height; turtle_theta = point(x, y, x1, y01); turtle_x = x; turtle_y = y; turn(left_angle); generate(g, x1, y01, left_width_factor * width, left_height_factor * height, left_angle, level); turtle_theta = point(x, y, x1, y01); turn(-right_angle); generate(g, x1, y01, width, left_height_factor * height, right_angle, level); g.drawString("Fractal.java", 10, 10); }
private long normalizeMax(long l) { int exp = (int) Math.log10((double) l); long multiple = (long) Math.pow(10.0, exp); int i = (int) (l / multiple); l = (i + 1) * multiple; return l; }
public void paintIcon(Component c, Graphics g, int x, int y) { Color color = c == null ? Color.GRAY : c.getBackground(); // In a compound sort, make each succesive triangle 20% // smaller than the previous one. int dx = (int) (size / 2 * Math.pow(0.8, priority)); int dy = descending ? dx : -dx; // Align icon (roughly) with font baseline. y = y + 5 * size / 6 + (descending ? -dy : 0); int shift = descending ? 1 : -1; g.translate(x, y); // Right diagonal. g.setColor(color.darker()); g.drawLine(dx / 2, dy, 0, 0); g.drawLine(dx / 2, dy + shift, 0, shift); // Left diagonal. g.setColor(color.brighter()); g.drawLine(dx / 2, dy, dx, 0); g.drawLine(dx / 2, dy + shift, dx, shift); // Horizontal line. if (descending) { g.setColor(color.darker().darker()); } else { g.setColor(color.brighter().brighter()); } g.drawLine(dx, 0, 0, 0); g.setColor(color); g.translate(-x, -y); }
public static String readableFileSize(long size) { if (size <= 0) return "0"; final String[] units = new String[] {"B", "KB", "MB", "GB", "TB"}; int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; }
/*------------------------------------------------------------------*/ double getInitialCausalCoefficientMirrorOnBounds(double[] c, double z, double tolerance) { double z1 = z, zn = Math.pow(z, c.length - 1); double sum = c[0] + zn * c[c.length - 1]; int horizon = c.length; if (0.0 < tolerance) { horizon = 2 + (int) (Math.log(tolerance) / Math.log(Math.abs(z))); horizon = (horizon < c.length) ? (horizon) : (c.length); } zn = zn * zn; for (int n = 1; (n < (horizon - 1)); n++) { zn = zn / z; sum = sum + (z1 + zn) * c[n]; z1 = z1 * z; } return (sum / (1.0 - Math.pow(z, 2 * c.length - 2))); } /* end getInitialCausalCoefficientMirrorOnBounds */
private Picture initialImage() { pic2 = new Picture(500, 600); pic1 = new Picture(500, 600); for (int x = 0; x < pic2.width(); x++) for (int y = 0; y < pic2.height(); y++) { double dist = 1.0 - Math.sqrt((x - 300) * (x - 300) + (y - 200) * (y - 200)) / 500; int red = (int) (dist < 0.5 ? 0 : Math.min(Math.pow(dist, 0.4) + Math.pow(dist - 0.5, 0.1), 1.0) * 255); int green = (int) (dist * 255); int blue = 0; pic2.set(x, y, new Color(red, green, blue)); } return pic2; }
public double getValue(DatanVector x) { double result; double a = sqrt2pi * x.getElement(1); if (a < small) f = big; else f = Math.log(a); result = (double) y.length * f; for (int i = 0; i < y.length; i++) { f = Math.pow((y[i] - x.getElement(0)), 2.) / (2. * x.getElement(1) * x.getElement(1)); result += f; } return result; }
// calculate and display amounts private void calculateJButtonActionPerformed(ActionEvent event) { resultJTextArea.setText("Rate (%)\tAmount after 10 years"); DecimalFormat dollars = new DecimalFormat("$0.00"); int principal = Integer.parseInt(principalJTextField.getText()); // for loop to calculate interest for (int rate = 5; rate <= 10; rate++) { double amount = (double) principal * Math.pow(1 + ((double) rate / 100), 10); resultJTextArea.append("\n" + rate + "\t" + dollars.format(amount)); } // end for } // end method calculateJButtonActionPerformed
protected void plotScatterDiagram() { // plot sample as one dimensional scatter plot and Gaussian double xmax = 5.; double xmin = -5.; DatanGraphics.openWorkstation(getClass().getName(), "E3Min_1.ps"); DatanGraphics.setFormat(0., 0.); DatanGraphics.setWindowInComputingCoordinates(xmin, xmax, 0., .5); DatanGraphics.setViewportInWorldCoordinates(-.15, .9, .16, .86); DatanGraphics.setWindowInWorldCoordinates(-.414, 1., 0., 1.); DatanGraphics.setBigClippingWindow(); DatanGraphics.chooseColor(2); DatanGraphics.drawFrame(); DatanGraphics.drawScaleX("y"); DatanGraphics.drawScaleY("f(y)"); DatanGraphics.drawBoundary(); double xpl[] = new double[2]; double ypl[] = new double[2]; // plot scatter diagram DatanGraphics.chooseColor(1); for (int i = 0; i < y.length; i++) { xpl[0] = y[i]; xpl[1] = y[i]; ypl[0] = 0.; ypl[0] = .1; DatanGraphics.drawPolyline(xpl, ypl); } // draw Gaussian corresponding to solution int npl = 100; xpl = new double[npl]; ypl = new double[npl]; double fact = 1. / (Math.sqrt(2. * Math.PI) * x.getElement(1)); double dpl = (xmax - xmin) / (double) (npl - 1); for (int i = 0; i < npl; i++) { xpl[i] = xmin + (double) i * dpl; ypl[i] = fact * Math.exp(-.5 * Math.pow((xpl[i] - x.getElement(0)) / x.getElement(1), 2.)); } DatanGraphics.chooseColor(5); DatanGraphics.drawPolyline(xpl, ypl); // draw caption String sn = "N = " + nny; numForm.setMaximumFractionDigits(3); numForm.setMinimumFractionDigits(3); String sx1 = ", x_1# = " + numForm.format(x.getElement(0)); String sx2 = ", x_2# = " + numForm.format(x.getElement(1)); String sdx1 = ", &D@x_1# = " + numForm.format(Math.sqrt(cx.getElement(0, 0))); String sdx2 = ", &D@x_2# = " + numForm.format(Math.sqrt(cx.getElement(1, 1))); caption = sn + sx1 + sx2 + sdx1 + sdx2; DatanGraphics.setBigClippingWindow(); DatanGraphics.chooseColor(2); DatanGraphics.drawCaption(1., caption); DatanGraphics.closeWorkstation(); }
public void showStats() { DecimalFormat twoPlaces = new DecimalFormat("0.00"); int sumd = 0, sumdsq = 0; int maxd = 0, mind = gSize - 1; double p, q; maxdCount = 0; p = CAGridStatic.params.pr; q = CAGridStatic.params.pl; for (int i = 0; i < gSize; i++) if (dCount[i] > maxdCount) maxdCount = dCount[i]; for (int i = 0; i < runCount; i++) { sumd = sumd + savedd[i]; sumdsq = sumdsq + saveddsq[i]; if (savedd[i] < mind) mind = savedd[i]; if (savedd[i] > maxd) maxd = savedd[i]; } runStats[0] = maxit * (p - q); // expected d runStats[1] = (maxit * (p + q) + maxit * (maxit - 1) * Math.pow(p - q, 2.0)); // expected dsq runStats[2] = (double) sumd / (double) (runCount); // av d from this run runStats[3] = ((double) sumdsq) / ((double) (runCount)); runStats[4] = maxdCount; if (runCount > 0) { System.out.println( "expected d: " + twoPlaces.format(runStats[0]) + " expected dsq " + twoPlaces.format(runStats[1])); System.out.println( "av d: " + twoPlaces.format(runStats[2]) + " av d sq " + twoPlaces.format(runStats[3])); System.out.println("range of d: " + mind + " to " + maxd); System.out.println("maxdCount " + maxdCount); System.out.println("runCount = " + runCount); /* for debug java.io.FileWriter file; try { file = new java.io.FileWriter("stuff.dat"); java.io.BufferedWriter buffer = new java.io.BufferedWriter(file); for (int i=0;i<runCount;i++){ buffer.write(savedd[i]+" "+saveddsq[i]+"\n"); } buffer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } }
// calculate and display amounts private void calculateJButtonActionPerformed(ActionEvent event) { // declare variables to store user input double principal = Double.parseDouble(principalJTextField.getText()); double rate = Double.parseDouble(interestRateJTextField.getText()); Integer integerObject = (Integer) yearsJSpinner.getValue(); Integer year = integerObject.intValue(); yearlyBalanceJTextArea.setText("Year\tAmount on Deposit"); DecimalFormat dollars = new DecimalFormat("$0.00"); // calculate the total value for each year for (int count = 1; count <= year; count++) { double amount = principal * Math.pow((1 + rate / 100), count); yearlyBalanceJTextArea.append("\n" + count + "\t" + dollars.format(amount)); } // end for } // end method calculateJButtonActionPerformed
public void makeRelationsButtonActionPerformed(ActionEvent evt) { System.out.println("In make relationships"); int k = stakeholders.size(); for (Iterator<Stakeholder> s = stakeholders.iterator(); s.hasNext(); ) { Stakeholder stakeholder = s.next(); int place = (int) Math.pow(2.0, (double) k); int random = (int) (Math.random() * place); place /= 2; System.out.println(random); for (int i = k - 1; i >= 0; i--) { System.out.printf("if(%d >= %d)\n", random, place); if (random >= place) { System.out.printf("%s.addI(%s)%n", stakeholder.getName(), stakeholders.get(i).getName()); stakeholder.addInfluence(stakeholders.get(i).getName(), (int) (Math.random() * 4)); random -= place; } place /= 2; } } }
private void removeFullRows() { int n_full = countFullRows(); score_label.addValue((int) (10 * Math.pow(2, n_full) - 10)); if (n_full == 0) return; sounds.playDestroyRows(n_full); if (num_rows_deleted / DELETED_ROWS_PER_LEVEL != (num_rows_deleted + n_full) / DELETED_ROWS_PER_LEVEL) { timer.faster(); level_label.addValue(n_full / DELETED_ROWS_PER_LEVEL + 1); level_label.repaint(); } rows_deleted_label.addValue(n_full); num_rows_deleted += n_full; for (int i = ROWS - 1; i >= 0; i--) while (rowIsFull(i)) removeRow(i); game_grid.repaint(); }
/** * Gets called when clicking the save button. Puts data back into Worker and fires * ListSelectionEvent in Worker, so that the 3D View is updated. */ public void save() { short[] tmpFrame = frame; changedStateSinceSave = false; short reihe = 0; for (int j = 0; j < 8; j++) { for (int i = 0; i < 8; i++) { reihe += ((short) Math.pow(2, i)) * ledStatus[i][j]; } tmpFrame[(8 * (li + 1) + j) - 8] = reihe; reihe = 0; } frame = tmpFrame; worker.getAnimation(animI).getFrame(frameI).setData(frame); ListSelectionEvent layerChanged = new ListSelectionEvent( LedFrame.frameList, LedFrame.frameList.getSelectedIndex(), LedFrame.frameList.getSelectedIndex(), false); LedFrame.valueChanged(layerChanged); dispose(); }
public void readFNum() { // work in nybbles: 0-9=0-9, a=. b=E, c=E-, d=rsvd e=neg f=end float f = 0; boolean neg = false; int exp = 0; int eval = 0; float mul = 1; byte work = data[pos++]; while (true) { if (work == (byte) 0xdd) { work = data[pos++]; } int nyb = (work >> 4) & 0xf; work = (byte) ((work << 4) | 0xd); if (nyb < 10) { if (exp != 0) { // working on the exponent eval = eval * 10 + nyb; } else if (mul == 1) { // working on an int f = f * 10 + nyb; } else { // working on decimal part f += nyb * mul; mul /= 10f; } } else if (nyb == 0xa) { // decimal mul = 0.1f; } else if (nyb == 0xb) { // E+ exp = 1; } else if (nyb == 0xc) { // E- exp = -1; } else if (nyb == 0xe) { // neg neg = true; } else { break; } } fnum = (neg ? -1 : 1) * f * (float) Math.pow(10, eval * exp); }
public boolean contains(Point p) { int distance = (int) (Math.sqrt(Math.pow(p.x - centre.x, 2) + Math.pow(p.y - centre.y, 2))); return (distance < size / 2); }
public double getValue(DatanVector x, double t) { return x.getElement(0) * Math.pow(t, x.getElement(1)); }
public void setDecimals(int decimals) { this.decimals = decimals; this.decimalsMultiplier = Math.pow(10.0, decimals); }
public void actionPerformed(ActionEvent ae) { String s = ae.getActionCommand(); if (s.equals("Dodawanie")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); wynik += "1"; textField1.setText(""); } else if (s.equals("Odejmowanie")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); wynik += "2"; textField1.setText(""); } else if (s.equals("Mnozenie")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); wynik += "3"; textField1.setText(""); } else if (s.equals("Dzielenie")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); wynik += "4"; textField1.setText(""); } else if (s.equals("Potegowanie")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); wynik += "5"; textField1.setText(""); } else if (s.equals("Pierwiastek")) { tekst = ""; tekst2 = ""; wynik = ""; tekst += textField1.getText(); int a = Integer.parseInt(tekst); f = (double) Math.sqrt(a); textField1.setText("" + zao.format(f)); } else if (s.equals("Wynik")) { tekst2 += textField1.getText(); int a = Integer.parseInt(tekst); int b = Integer.parseInt(tekst2); int w = Integer.parseInt(wynik); if (w == 1) { c = a + b; textField1.setText("" + c); } if (w == 2) { c = a - b; textField1.setText("" + c); } if (w == 3) { c = a * b; textField1.setText("" + c); } if (w == 4) { c = a / b; textField1.setText("" + c); } if (w == 5) { c = (int) Math.pow(a, b); textField1.setText("" + c); } } else if (s.equals("Czysc")) { tekst = ""; tekst2 = ""; wynik = ""; textField1.setText(""); } }
class LJ3MD { static final int D = 3; public int N = 256; private int DOF = N * D - D * (D + 1) / 2; double rho = 0.256; double dt = 0.002; // time step for integrating Newton's equation public double L = 10.0; // side of the box public double Vol = 1000.0; double rc = 2.5; // cut-off radius double epsilon = 0.001; // interaction strength public double kT = 1.0; // temperature times Boltzmann constant double x[][]; // position, from 0 to 1 double v[][], f[][]; // velocity and force double xwrap[][]; // wrapped coordinates double K, U, Us, E; // kinetic, potential, and total energy double Vir, p; // virial and pressure boolean thermostat = true; // use thermostat boolean ljPotential = true; double ushift; double Utail; // potential energy tail correction double ptail; // pressure tail correction int step; // simulation steps double boltK = 1.38 * Math.pow(10, -23); Ave avU = new Ave(), avK = new Ave(), avp = new Ave(); /** constructor */ LJ3MD(double den) { init(den); } /** initialize system */ public void init(double den) { int i, j, k, id; DOF = N * D - D * (D + 1) / 2; setDensity(den); step = 0; x = new double[N][D]; v = new double[N][D]; f = new double[N][D]; xwrap = new double[N][D]; for (id = 0; id < N; id++) for (j = 0; j < D; j++) v[id][j] = 0.0; int N1 = (int) (pow(2 * N, 1.0 / D) + .999999); // # of particles per side (cubic lattic) double a = 1. / N1; for (id = 0, i = 0; i < N1 && id < N; i++) // place particles on a cubic lattice for (j = 0; j < N1 && id < N; j++) for (k = 0; k < N1 && id < N; k++) { if ((i + j + k) % 2 != 0) continue; x[id][0] = a * (i + .5); x[id][1] = a * (j + .5); x[id][2] = a * (k + .5); id++; } } /** set density and recalculate tail corrections */ void setDensity(double den) { rho = den; Vol = N / rho; L = pow(Vol, 1.0 / D); /* compute shifts and tail corrections */ if ((rc = 2.5) > .5 * L) rc = .5 * L; double irc = 1. / rc, irc3 = irc * irc * irc, irc6 = irc3 * irc3; ushift = 4.0 * irc6 * (irc6 - 1); Utail = 8.0 * PI / 9 * rho * N * (irc6 - 3) * irc3; ptail = 16.0 * PI / 9 * rho * rho * (irc6 - 1.5) * irc3; clearData(); } void clearData() { step = 0; avU.clear(); avK.clear(); avp.clear(); } /** integrate Newton's equation by one step, velocity Verlet */ void vv() { double dth = dt * .5, dtl = dt / L; for (int id = 0; id < N; id++) // velocity-verlet, first half for (int d = 0; d < D; d++) { v[id][d] += f[id][d] * dth; x[id][d] += v[id][d] * dtl; } force(); // compute force for (int id = 0; id < N; id++) // velocity-verlet, second half for (int d = 0; d < D; d++) v[id][d] += f[id][d] * dth; rmcom(); // rm angular momentum however isn't good idea due to // pbc and minimal image convension K = vrescale(0.02); // compute kinetic energy and adjust velocity E = K + Us; step++; avU.add(U); avK.add(K); avp.add(p); } /** calculate potential energy and force half-box cutoff, minimal distance image */ double xij[] = new double[D]; void force() { int i, j, d, prcnt = 0; double invr2, invr6, r2, fscal, tmp; // clear the force and energy U = 0.0; Vir = 0.0; for (i = 0; i < N; i++) for (d = 0; d < D; d++) f[i][d] = 0.0; // loop over pairs of particles and compute energy (1) Lennard-Jones, (2) WCA; // LJ 12-6 for (i = 0; i < N - 1; i++) { for (j = i + 1; j < N; j++) { rv3Diff(xij, x[i], x[j]); vpbc(xij); r2 = vsqr(xij); // (1) if (ljPotential) { if (r2 > rc * rc) continue; // if r > rc: break invr2 = 1.0 / r2; invr6 = invr2 * invr2 * invr2; fscal = invr6 * (48.0 * invr6 - 24.0); Vir += fscal; fscal *= invr2; for (d = 0; d < D; d++) { tmp = xij[d] * fscal; f[i][d] += tmp; f[j][d] -= tmp; } U += 4.0 * invr6 * (invr6 - 1.0); } // (2) else { if (r2 > 1.2599210492 * rc * rc) { } else { invr2 = 1.0 / r2; invr6 = invr2 * invr2 * invr2; fscal = invr6 * (48.0 * invr6 - 24.0); Vir += fscal; fscal *= invr2; for (d = 0; d < D; d++) { tmp = xij[d] * fscal; f[i][d] += tmp; f[j][d] -= tmp; } U += 4.0 * invr6 * (invr6 - 1.0) + epsilon; } } prcnt++; } } Us = U - prcnt * ushift; U += Utail; p = rho * kT + Vir / (3 * Vol) + ptail; } Random rng = new Random(); /** velocity rescaling thermostat */ double vrescale(double dt) { double ek1 = getEKin(); if (!thermostat) return ek1; double ekav = .5f * kT * DOF; double amp = 2 * sqrt(ek1 * ekav * dt / DOF); double ek2 = ek1 + (ekav - ek1) * dt + amp * rng.nextGaussian(); if (ek2 < 0) ek2 = ek1; double s = sqrt(ek2 / ek1); for (int i = 0; i < N; i++) for (int d = 0; d < D; d++) v[i][d] *= s; return ek2; } /** remove motion of the center of mass */ void rmcom() { for (int d = 0; d < D; d++) { // remove the center of mass motion double vc = 0.0; for (int id = 0; id < N; id++) vc += v[id][d]; vc /= N; for (int id = 0; id < N; id++) v[id][d] -= vc; } } private void rv3Diff(double c[], double a[], double b[]) { c[0] = a[0] - b[0]; c[1] = a[1] - b[1]; c[2] = a[2] - b[2]; } private double rv3Dot(double a[], double b[]) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } /** return the kinetic energy */ double getEKin() { double ek = 0.0; for (int i = 0; i < N; i++) ek += rv3Dot(v[i], v[i]); return .5 * ek; } /** image with the minimal distance */ double pbc(double a) { return L * (a - ((int) (a + 1000.5) - 1000)); } void vpbc(double v[]) { v[0] = pbc(v[0]); v[1] = pbc(v[1]); v[2] = pbc(v[2]); } double vsqr(double v[]) { return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; } /** wrap coordinates back into box */ public double[][] getXWrap() { for (int i = 0; i < N; i++) for (int d = 0; d < D; d++) { double xx = x[i][d] + 1000.0; xwrap[i][d] = (xx - (int) xx) * L; } return xwrap; } }
/** Get an image based on index numbers */ public BufferedImage getIndexedImage( int x, int y, int zoom, int cacheZoom, GMapListener listener) { if (listener != null) { if (!getGDataSource().isCached(x, y, zoom)) { listener.updateGMapPainting(); listener.updateGMapMessage(GMap.MESSAGE_DOWNLOADING); } else { listener.updateGMapMessage(GMap.MESSAGE_PAINTING); } } BufferedImage thumbImage = getGDataSource().getImage(x, y, zoom, true); if (thumbImage == null) return defaultImage; // if we dont have to paint cache, return here if (cacheZoom == (GPhysicalPoint.MIN_ZOOM - 1) || cacheZoom >= zoom) return thumbImage; BufferedImage paintedImage = new BufferedImage( GDataSource.sourceSize.width, GDataSource.sourceSize.height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = paintedImage.createGraphics(); graphics2D.drawImage( thumbImage, 0, 0, GDataSource.sourceSize.width, GDataSource.sourceSize.height, null); // now lets move to painting the cache double imageNum = Math.pow(2, zoom - cacheZoom); // draw cache lines int startX = (int) (imageNum * x); int startY = (int) (imageNum * y); // get composite to restore later, set new transparent composite Composite originalComposite = graphics2D.getComposite(); graphics2D.setComposite(opacity40); // draw grid for (int i = 0; i < imageNum; i++) { for (int j = 0; j < imageNum; j++) { // points Point upperLeft = new Point( (int) (GDataSource.sourceSize.width / imageNum) * i, (int) (GDataSource.sourceSize.height / imageNum) * j); Dimension size = new Dimension( (int) (GDataSource.sourceSize.width / imageNum), (int) (GDataSource.sourceSize.height / imageNum)); // draw lines graphics2D.setColor(new Color(100, 100, 100)); graphics2D.drawLine(upperLeft.x, upperLeft.y, upperLeft.x + size.width, upperLeft.y); graphics2D.drawLine(upperLeft.x, upperLeft.y, upperLeft.x, upperLeft.y + size.height); // check if file exists if (getGDataSource().isCached(startX + i, startY + j, cacheZoom)) graphics2D.setColor(Color.RED); else graphics2D.setColor(new Color(155, 155, 155)); // shade rectangle graphics2D.fillRect(upperLeft.x, upperLeft.y, size.width, size.height); } } // restore composite graphics2D.setComposite(originalComposite); return paintedImage; }
public int ai_move(int[][] board) { if (running) { System.out.println( "This AI appears to be running multiple ai_moves simultaneously. That can't be right."); } running = true; try { // System.out.println(2 + Math.random()); if (recording) { if (out == null) { try { int ind = 1; File f = null; while (true) { try { Scanner sc = new Scanner(new File("AIReplay" + ind + ".txt")); ind++; } catch (Exception e) { break; } } out = new PrintWriter(new File("AIReplay" + ind + ".txt")); filename = "AIReplay" + ind + ".txt"; out.println("AI Version: " + VERSION); } catch (Exception e) { System.out.println("Could not write to file."); } } fprint(board); } // if (fml == null) fml = new PrintWriter (new File("fmldebug.txt")); if (thisAIIsCheating && max(board) < 8) { board[0][0] = GameGUI.win_target; } if (debug2) sc.nextLine(); if (debug2) print(board); if (debug) System.out.println("New cycle."); if (debug) sc.nextLine(); if (dumbai) name += "Dumby"; turn++; if (!queue.isEmpty()) { int temp = queue.removeFirst(); if (temp > 0) { running = false; return temp; } } int boardsum = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { boardsum += board[i][j]; } } boolean report = debug; /*if (Math.random() < 0.0001) { report = true; for (int i = 0; i < 4; i++) { System.out.println(Arrays.toString(board[i])); } for (int i = 0; i < 4; i++) { System.out.println(movable(board, i)); } System.out.println(); sc.nextLine(); }*/ if (dumbai) { if (!name.endsWith("Dumby")) name += "Dumby"; System.out.println(turn); running = false; if (turn % 600 == 599) return KeyEvent.VK_DOWN; if (turn % 3 == 0) return KeyEvent.VK_UP; if (turn % 6 < 3) return KeyEvent.VK_LEFT; return KeyEvent.VK_RIGHT; } else { if (name.indexOf(".") < 0) name += VERSION; } // gamestart processing /*if(board[0][0] == 0) { if (board[1][0] > board[0][1]) { return KeyEvent.VK_UP; } if (board[1][0] < board[0][1]) { return KeyEvent.VK_LEFT; } if (Math.random() < 0.5) return KeyEvent.VK_UP; return KeyEvent.VK_LEFT; }*/ long[] pref = {10, 20, 1, 1}; // LEFT, UP, RIGHT, DOWN // check if moving right/down is safe boolean occupied = true; for (int i = 0; i < 4; i++) { if (board[0][i] == 0) occupied = false; if (i < 3 && board[0][i] == board[0][i + 1]) occupied = false; } if (!occupied) { // pref[2] -= 100000000; } occupied = true; for (int i = 0; i < 4; i++) { if (board[i][0] == 0) occupied = false; if (i < 3 && board[i][0] == board[i + 1][0]) occupied = false; } if (!occupied) { // pref[3] -= 100000000; } pref[0] += 5; pref[1] += 5; // System.out.println(6 + Math.random()); // simulate sum_board = sum(board); delta_sum_board_7over8 = delta(sum_board * 7 / 8); if (debug) print(board); max_depth = 0; for (int m = 0; m < 4; m++) { if (debug) System.out.println("Now testing move: " + m); int[][] sim = simulate(board, m); if (Arrays.deepEquals(sim, board)) { if (out != null) out.println("Move " + m + " invalid; skipping"); if (GameGUI.out != null) GameGUI.out.println("Move " + m + " invalid; skipping"); continue; } long worst = (long) 1999999999 * 1000000000; long avg = 0; int numt = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (sim[i][j] > 0) continue; sim[i][j] = 2; long temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1); if (temp < worst) worst = temp; avg += 9 * temp; sim[i][j] = 4; temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1); if (temp < worst) worst = temp; avg += temp; sim[i][j] = 0; numt += 10; } } if (countBlank(sim) == 0) { long temp = predictor(sim, iter_max / (int) pow((countBlank(sim) + 1), 2), 1); if (temp < worst) worst = temp; avg += temp; numt++; } avg /= numt; worst = (worst_weight * worst + avg) / (worst_weight + 1); if (countBlank(sim) >= 8 && max(board) < 64) worst = avg; if (debug || debug2) System.out.println("Move " + m + " final eval: " + worst); if (out != null) out.println("Move " + m + " final eval: " + worst); if (GameGUI.out != null) GameGUI.out.println("Move " + m + " final eval: " + worst); pref[m] += worst; } if (debug2) System.out.println("Max depth: " + max_depth); if (out != null) out.println("Max depth: " + max_depth); if (GameGUI.out != null) GameGUI.out.println("Max depth: " + max_depth); // System.out.println(5 + Math.random()); // process output int[] dir = new int[4]; dir[0] = KeyEvent.VK_LEFT; dir[1] = KeyEvent.VK_UP; dir[2] = KeyEvent.VK_RIGHT; dir[3] = KeyEvent.VK_DOWN; if (report) System.out.println("Pref: " + Arrays.toString(pref)); for (int i = 0; i < 4; i++) { int best = 0; for (int j = 0; j < 4; j++) { if (pref[j] > pref[best]) { best = j; } } pref[best] = Long.MIN_VALUE; if (movable(board, best)) { if (report) { report = false; if (debug) System.out.println("Chosen: " + best); if (debug) sc.nextLine(); } // if (pref[best] < -50000000) queue.add(best - 2); running = false; return dir[best]; } // System.out.println("Unmovable: " + best); // System.out.println("Pref: " + Arrays.toString(pref)); } System.out.println("???"); for (int i = 0; i < 4; i++) { System.out.println(Arrays.toString(board[i])); } // sc.nextLine(); } catch (Exception e) { e.printStackTrace(); } running = false; return KeyEvent.VK_LEFT; }
protected void compute() { n = (int) ni[0].parseInput(); t0 = ni[1].parseInput(); deltat = ni[2].parseInput(); x1 = ni[3].parseInput(); x2 = ni[4].parseInput(); sigma = ni[5].parseInput(); // generate data points t = new DatanVector(n); y = new DatanVector(n); dy = new DatanVector(n); rand = DatanRandom.standardNormal(n); for (int i = 0; i < n; i++) { t.setElement(i, t0 + (double) i * deltat); y.setElement(i, x1 * Math.pow(t.getElement(i), x2) + sigma * rand[i]); dy.setElement(i, sigma); } // find 1st approximation of unknowns by method of log-log plot tlog = new double[n]; ylog = new double[n]; dellog = new double[n]; int npos = 0; for (int i = 0; i < n; i++) { if (t.getElement(i) > 0. && y.getElement(i) > 0.) { tlog[npos] = Math.log(t.getElement(i)); ylog[npos] = Math.log(y.getElement(i)); dellog[npos] = 1.; npos++; } } DatanVector vtlog = new DatanVector(npos); DatanVector vylog = new DatanVector(npos); DatanVector vdellog = new DatanVector(npos); for (int j = 0; j < npos; j++) { vtlog.setElement(j, tlog[j]); vylog.setElement(j, ylog[j]); vdellog.setElement(j, dellog[j]); } LsqPol lp = new LsqPol(vtlog, vylog, vdellog, 2); x = lp.getResult(); x.setElement(0, Math.exp(x.getElement(0))); df.writeLine(" x = " + x.toString()); // perform fit int[] list = {1, 1}; powerlaw = new Powerlaw(); LsqNon ln = new LsqNon(t, y, dy, x, list, powerlaw); x = ln.getResult(); x1 = x.getElement(0); x2 = x.getElement(1); cov = ln.getCovarianceMatrix(); delx1 = Math.sqrt(cov.getElement(0, 0)); delx2 = Math.sqrt(cov.getElement(1, 1)); rho = cov.getElement(1, 0) / (delx1 * delx2); m = ln.getChiSquare(); p = 1. - StatFunct.cumulativeChiSquared(m, n - 1); // curve of fitted exponential xpl = new double[1001]; ypl = new double[1001]; dpl = (double) (n - 1) * deltat / 1000.; for (int i = 0; i < 1001; i++) { xpl[i] = t0 + (double) i * dpl; ypl[i] = x1 * Math.pow(xpl[i], x2); } // prepare data points for plotting datx = new double[n]; daty = new double[n]; datsx = new double[n]; datsy = new double[n]; datrho = new double[n]; for (int i = 0; i < n; i++) { datx[i] = t.getElement(i); daty[i] = y.getElement(i); datsx[i] = 0.; datsy[i] = dy.getElement(i); datrho[i] = 0.; } // display data and fitted curve caption = "x_1#=" + String.format(Locale.US, "%5.2f", x1) + ", x_2#=" + String.format(Locale.US, "%5.2f", x2) + ", &D@x_1#=" + String.format(Locale.US, "%5.2f", delx1) + ", &D@x_2#=" + String.format(Locale.US, "%5.2f", delx2) + ", &r@=" + String.format(Locale.US, "%5.2f", rho) + ", M=" + String.format(Locale.US, "%5.2f", m) + ", P=" + String.format(Locale.US, "%6.4f", p); new GraphicsWithDataPointsAndPolyline( getClass().getName(), "", xpl, ypl, 1, .3, datx, daty, datsx, datsy, datrho, "t", "y", caption); }
public void processSectionSpline(boolean shiftDown) { mCurrPC.setBatchModeOn(); if (!shiftDown) mCurrPC.unselectAll(); // loop on spline pts for (int s = 0; s < mSplinePoints.size() - 2; s++) { Point p1 = (Point) mSplinePoints.elementAt(s); Point p2 = (Point) mSplinePoints.elementAt(s + 1); int x1 = p1.x - mLeft - 5; int y1 = p1.y - mTop - 5; int x2 = p2.x - mLeft - 5; int y2 = p2.y - mTop - 5; // construct the search polygon double dx = x1 - x2; double dy = y1 - y2; int width1 = ComputeSectionPixelWidth(p1); int width2 = ComputeSectionPixelWidth(p2); if (dx == 0 && dy == 0) return; double dist = (double) Math.pow(dx * dx + dy * dy, 0.5f); double p1x = x1 + (double) width1 * (-dy / dist); double p1y = y1 + (double) width1 * (dx / dist); double p2x = x1 - (double) width1 * (-dy / dist); double p2y = y1 - (double) width1 * (dx / dist); double p3x = x2 + (double) width2 * (-dy / dist); double p3y = y2 + (double) width2 * (dx / dist); double p4x = x2 - (double) width2 * (-dy / dist); double p4y = y2 - (double) width2 * (dx / dist); Polygon srcArea = new Polygon(); srcArea.addPoint((int) p2x, (int) p2y); srcArea.addPoint((int) p1x, (int) p1y); srcArea.addPoint((int) p3x, (int) p3y); srcArea.addPoint((int) p4x, (int) p4y); // search for matches byte[] currFilterResults = fdm.getResults(); double[] yArray1 = getYArray1(); double[] xArray1 = getXArray1(); double[] yArray2 = getYArray2(); double[] xArray2 = getXArray2(); mCurrPC.setBatchModeOn(); for (int i = 0; i < mCurrPC.getSize(); i++) { if (!mIgnoreFilter && (mCurrPC.isDeleted(i) || currFilterResults[i] != 4 || !mCurrPC.isSelectedLayer(i))) continue; double yi = yArray1[i]; double xi = xArray1[i]; double xi2 = Float.NaN; double yi2 = Float.NaN; double xx2 = Float.NaN; double yy2 = Float.NaN; // correct the X value if necessary xi = correctX(xi); double xx1 = (xi - winXOrigin) * winXScale; double yy1 = (yi - winYOrigin) * winYScale; // correct the Y coordinate if necessary yy1 = correctY(yy1); if (!isYAxisScaler()) { yi2 = yArray2[i]; yy2 = (yi2 - winYOrigin) * winYScale; ; yy2 = correctY(yy2); } else yy2 = yy1; if (!isXAxisScaler()) { xi2 = xArray2[i]; xi2 = correctX(xi2); xx2 = (xi2 - winXOrigin) * winXScale; } else xx2 = xx1; if (srcArea.contains(new Point((int) xx1, (int) yy1)) || srcArea.contains(new Point((int) xx2, (int) yy2))) { mCurrPC.select(i); } } } // for splines mSplinePoints.removeAllElements(); mViewManager.invalidateAllViews(); mCurrPC.setBatchModeOff(); }