Beispiel #1
0
  /**
   * Uses the Haversine formula to calculate the distnace between to lat-long coordinates
   *
   * @param latitude1 The first point's latitude
   * @param longitude1 The first point's longitude
   * @param latitude2 The second point's latitude
   * @param longitude2 The second point's longitude
   * @return The distance between the two points in meters
   */
  public static double CalculateDistance(
      double latitude1, double longitude1, double latitude2, double longitude2) {
    /*
    Haversine formula:
    A = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    C = 2.atan2(√a, √(1−a))
    D = R.c
    R = radius of earth, 6371 km.
    All angles are in radians
    */

    double deltaLatitude = Math.toRadians(Math.abs(latitude1 - latitude2));
    double deltaLongitude = Math.toRadians(Math.abs(longitude1 - longitude2));
    double latitude1Rad = Math.toRadians(latitude1);
    double latitude2Rad = Math.toRadians(latitude2);

    double a =
        Math.pow(Math.sin(deltaLatitude / 2), 2)
            + (Math.cos(latitude1Rad)
                * Math.cos(latitude2Rad)
                * Math.pow(Math.sin(deltaLongitude / 2), 2));

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return 6371 * c * 1000; // Distance in meters
  }
Beispiel #2
0
  private Double CosineSimilarity(HashMap<String, Double> table1, HashMap<String, Double> table2)
      throws Exception {
    if (table1.size() != table2.size()) {
      throw new Exception("Table sizes must be equal");
    }

    // length of table 1
    double length1 = 0;
    double length2 = 0;

    // Double firstValue;
    double secValue;

    // sum of vector multiplication
    double svMul = 0;

    for (Entry<String, Double> kv : table1.entrySet()) {
      length1 += Math.pow(kv.getValue(), 2);

      secValue = table2.get(kv.getKey());
      length2 += Math.pow(secValue, 2);

      svMul += secValue * kv.getValue();
    }

    length1 = Math.sqrt(length1);
    length2 = Math.sqrt(length2);

    return Double.parseDouble(NumericFormat.getNumberFormated(svMul / (length1 * length2)));
  }
    public Double eval(Double gamma) {
      double c1 = 0.0;
      double c3 = -1.0 / (double) Math.sqrt(2.0 * variance);
      double sum = 0.0;

      double cpart = -0.5 * Math.log(Math.sqrt(2.0 * Math.PI * variance));

      for (Integer i : transcripts.get(gammat)) {
        c1 += cpart;
        double pi = 0.0;

        for (int t = 0; t < fiveprime.length; t++) {
          if (transcripts.get(t).contains(i)) {
            double gammai = gammat == t ? gamma : gammas[t][gammak];
            double dit = delta(i, t);

            double pit = gammai * Math.exp(-lambda * dit);
            pi += pit;
          }
        }

        double zi = Math.log(pi);
        double err = data.values(i)[channels[gammak]] - zi;

        sum += (err * err);
      }

      return c1 + c3 * sum;
    }
Beispiel #4
0
 public Object getData(final WModelIndex index, int role) {
   if (role != ItemDataRole.DisplayRole) {
     return super.getData(index, role);
   }
   double delta_y = (this.yEnd_ - this.yStart_) / (this.getColumnCount() - 2);
   if (index.getRow() == 0) {
     if (index.getColumn() == 0) {
       return 0.0;
     }
     return this.yStart_ + (index.getColumn() - 1) * delta_y;
   }
   double delta_x = (this.xEnd_ - this.xStart_) / (this.getRowCount() - 2);
   if (index.getColumn() == 0) {
     if (index.getRow() == 0) {
       return 0.0;
     }
     return this.xStart_ + (index.getRow() - 1) * delta_x;
   }
   double x;
   double y;
   y = this.yStart_ + (index.getColumn() - 1) * delta_y;
   x = this.xStart_ + (index.getRow() - 1) * delta_x;
   return 4
       * Math.sin(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)))
       / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
 }
    public Double eval(Double lmbda) {
      double c1 = 0.0;
      double c3 = -1.0 / (double) Math.sqrt(2.0 * variance);
      double sum = 0.0;

      double cpart = -0.5 * Math.log(Math.sqrt(2.0 * Math.PI * variance));

      for (int i = 0; i < data.size(); i++) {
        for (int k = 0; k < channels.length; k++) {
          c1 += cpart;
          double pi = 0.0;

          for (Integer t : transcripts.keySet()) {
            if (transcripts.get(t).contains(i)) {
              double dit = delta(i, t);
              double gammai = gammas[t][k];
              double pit = gammai * Math.exp(-lmbda * dit);
              pi += pit;
            }
          }

          double zi = Math.log(pi);
          double err = data.values(i)[channels[k]] - zi;

          sum += (err * err);
        }
      }

      return c1 + c3 * sum;
    }
 public void mouseReleased(MouseEvent e) {
   left_mouse_pressed = false;
   double kvadrat = Math.sqrt(angleX * angleX + angleY * angleY);
   double tempx = angleX / kvadrat;
   double tempy = Math.sqrt(1 - tempx * tempx);
   if (angleY < 0) tempy = -tempy;
   Bullet b = new Bullet();
   boolean next = false;
   if (type_bullet1 == true && count_sphere > 0) {
     b = new Sphere();
     count_sphere--;
     next = true;
   }
   if (type_bullet2 == true && count_fireball > 0) {
     b = new FireBall();
     count_fireball--;
     next = true;
   }
   if (type_bullet3 == true && count_rocket > 0) {
     b = new Rocket();
     count_rocket--;
     next = true;
   }
   if (next == true) {
     b.bullet_x = player.getX() + 52 + 5 * Math.cos(angle); // + 50; //koef;
     b.bullet_y = player.getY() + 49 + 5 * Math.sin(angle); // player.getY() + 35; //25;
     b.current_direction_x = tempx;
     b.current_direction_y = tempy;
     bullet.addElement(b);
     allow_shoot = false;
   }
 }
Beispiel #7
0
  private double rec(int idx, double rem) {
    if (idx >= 3) {
      return rem / walkSpeed;
    }

    double ans = INF;
    double left = 0;
    double right = rem;

    for (int iter = 0; iter < 100; iter++) {
      double m1 = left + (right - left) / 3.0;
      double m2 = right - (right - left) / 3.0;

      double a1 = rec(idx + 1, rem - m1) + Math.sqrt(sq(a[idx][0]) + sq(m1)) / a[idx][1];
      ans = Math.min(ans, a1);

      double a2 = rec(idx + 1, rem - m2) + Math.sqrt(sq(a[idx][0]) + sq(m2)) / a[idx][1];
      ans = Math.min(ans, a2);

      if (a1 < a2) {
        right = m2;
      } else {
        left = m1;
      }
    }

    return ans;
  }
Beispiel #8
0
  /**
   * This helper method calculates the repulsive forces acting on a node from all the other nodes in
   * the graph. BIG O( number of nodes )
   *
   * <p>There is a repulsive force between every nodes depending on the distance separating them and
   * their size.
   *
   * @param current node to calculate forces for.
   */
  private void calculateNodeRepulsiveForces(Node current) {
    Iterator<Node> inner = controller.getNodeIterator();
    int current_radius, n_radius, dx, dy;
    Node n;
    current_radius =
        (int) Math.sqrt(Math.pow(current.getWidth(), 2) + Math.pow(current.getHeight(), 2));
    while (inner.hasNext()) {
      n = inner.next();
      if (n != current) {
        dx = current.getX() - n.getX();
        dy = current.getY() - n.getY();
        n_radius = (int) Math.sqrt(Math.pow(n.getWidth(), 2) + Math.pow(n.getHeight(), 2));

        // only repel if nodes are connected or within diameter * MAX_REPEL_DISTANCE
        //  if (Math.sqrt(dx * dx + dy * dy) < (Math.max(current_radius, n_radius) *
        // MAX_REPEL_MULTIPLIER)) {
        double l = (dx * dx + dy * dy) + .1;
        if (l > 0) {
          // current.setVX(current.getVX() + dx * (current_radius * SPACING) / l);
          // current.setVY(current.getVY() + dy * (current_radius * SPACING) / l);

          current.accelx += (dx * REPULSION / (l)) / current.weight;
          current.accely += (dy * REPULSION / (l)) / current.weight;
          // current.accelx += (dx * SPACING / (l * .5)) / current.weight;
          // current.accely += (dy * SPACING / (l * .5)) / current.weight;
          // n.accelx += (dx * SPACING / (l * -0.5)) / n.weight;
          // n.accely += (dy * SPACING / (l * -0.5)) / n.weight;

        }
        //  }
      }
    }
  }
  /**
   * Calculates word order similarity between the sentences, with weighted words
   *
   * @param s1 sentence 1
   * @param s2 sentence 2
   * @param weights1 of sentence 1
   * @param weights2 of sentence 2
   * @return Word order similarity value
   */
  public double orderSimilarity(
      List<double[]> s1,
      List<double[]> s2,
      List<double[]> weights1,
      List<double[]> weights2,
      String sent2,
      String unique) {
    double[] s1Dist = s1.get(0);
    double[] s1Friend = s1.get(1);
    double[] s2Dist = s2.get(0);
    double[] s2Friend = s2.get(1);
    double[] r1 = new double[s1Dist.length];
    double[] r2 = new double[s2Dist.length];
    String[] sent = sent2.split(" ");
    String[] un = unique.split(" ");
    String word;

    // Specifies word order vectors for either sentence.
    // Threshold specifies that words can be seen as the same if similar enough
    // If same word not found in unique sentence, the order value is 0
    for (int i = 0; i < r1.length; i++) {
      if (s1Dist[i] == 1.0) {
        r1[i] = i + 1;
      } else if (s1Dist[i] >= threshold) {
        r1[i] = s1Friend[i] + 1;

      } else {
        r1[i] = 0;
      }
    }
    for (int i = 0; i < r2.length; i++) {
      if (s2Dist[i] == 1.0) {
        word = un[i];
        r2[i] = Arrays.asList(sent).indexOf(word) + 1;
      } else if (s2Dist[i] >= threshold) {
        r2[i] = s2Friend[i] + 1;

      } else {
        r2[i] = 0.0;
      }
    }
    double numerator = 0.0;
    double denominator = 0.0;
    // Calculate order similarity while avoiding division by 0
    for (int i = 0; i < r1.length; i++) {
      numerator = numerator + Math.pow((r1[i] - r2[i]) * weights1.get(0)[i], 2);
      denominator = denominator + Math.pow((r1[i] + r2[i]) * weights1.get(0)[i], 2);
    }
    numerator = Math.sqrt(numerator);
    denominator = Math.sqrt(denominator);
    if (denominator == 0.0) {
      numerator = 1;
      denominator = 1;
    }

    return numerator / denominator;
  }
Beispiel #10
0
      /**
       * The <code>deliverByte</code> method delivers bytes to receiver
       *
       * @param oneBitBeforeNow
       */
      private void deliverByte(long oneBitBeforeNow) {
        List<Transmission> it = getIntersection(oneBitBeforeNow - BYTE_SIZE);
        if (it != null) { // there is a transmission
          boolean one = false;
          double rssi = 0.0;
          double SNR = 0;
          assert it.size() > 0;
          for (Transmission t : it) {
            if (one) { // more than one transmission
              double I =
                  medium.arbitrator.computeReceivedPower(
                      t, Receiver.this, (int) clock.cyclesToMillis(clock.getCount()));
              // add interference to received power in linear scale
              rssi = 10 * Math.log10(Math.pow(10, rssi / 10) + Math.pow(10, I / 10));
              SNR = SNR - I;
            } else { // only one transmission - no interference -
              one = true;
              Pr =
                  medium.arbitrator.computeReceivedPower(
                      t, Receiver.this, (int) clock.cyclesToMillis(clock.getCount()));
              Pn = medium.arbitrator.getNoise((int) clock.cyclesToMillis(clock.getCount()));
              rssi = Pr;
              SNR = Pr - Pn;
            }
          }
          double snr = Math.pow(10D, (SNR / 10D));
          // ebno = snr / spectral efficiency = snr / log(1 + snr)
          double ebno = snr / Math.log(1 + snr);
          // BER vs Ebno in AWGN channel
          double x = Math.sqrt(2 * ebno);
          double x2 = Math.pow(x, 2);
          double BER = Math.exp(-x2 / 2) / (1.64D * x + Math.sqrt(0.76D * (x2) + 4D));
          setBER(BER);
          setRSSI(rssi);
          // merge transmissions into a single byte and send it to receiver
          // we return val in order to get rssi and corr value
          char val =
              medium.arbitrator.mergeTransmissions(
                  Receiver.this,
                  it,
                  oneBitBeforeNow - BYTE_SIZE,
                  (int) clock.cyclesToMillis(clock.getCount()));
          // store high byte for corrupted bytes
          int newval = (int) (val & 0xff00);
          newval |= (int) (0xff & nextByte(true, (byte) val));
          val = (char) newval;
          if (probeList != null) probeList.fireAfterReceive(Receiver.this, val);
          clock.insertEvent(this, cyclesPerByte);

        } else { // no transmissions intersect
          // all transmissions are over.
          locked = false;
          nextByte(false, (byte) 0);
          if (probeList != null) probeList.fireAfterReceiveEnd(Receiver.this);
          clock.insertEvent(this, leadCycles);
        }
      }
  double fitnessFunction(Solution individual, double[] lambda) {
    double fitness;
    fitness = 0.0;

    if (functionType_.equals("_TCHE1")) {
      double maxFun = -1.0e+30;

      for (int n = 0; n < problem_.getNumberOfObjectives(); n++) {
        double diff = Math.abs(individual.getObjective(n) - z_[n]);

        double feval;
        if (lambda[n] == 0) {
          feval = 0.0001 * diff;
        } else {
          feval = diff * lambda[n];
        }
        if (feval > maxFun) {
          maxFun = feval;
        }
      } // for

      fitness = maxFun;
    } // if
    else if (functionType_.equals("_AGG")) {
      double sum = 0.0;
      for (int n = 0; n < problem_.getNumberOfObjectives(); n++) {
        sum += (lambda[n]) * individual.getObjective(n);
      }

      fitness = sum;

    } else if (functionType_.equals("_PBI")) {
      double d1, d2, nl;
      double theta = 5.0;

      d1 = d2 = nl = 0.0;

      for (int i = 0; i < problem_.getNumberOfObjectives(); i++) {
        d1 += (individual.getObjective(i) - z_[i]) * lambda[i];
        nl += Math.pow(lambda[i], 2.0);
      }
      nl = Math.sqrt(nl);
      d1 = Math.abs(d1) / nl;

      for (int i = 0; i < problem_.getNumberOfObjectives(); i++) {
        d2 += Math.pow((individual.getObjective(i) - z_[i]) - d1 * (lambda[i] / nl), 2.0);
      }
      d2 = Math.sqrt(d2);

      fitness = (d1 + theta * d2);
    } else {
      System.out.println("MOEAD.fitnessFunction: unknown type " + functionType_);
      System.exit(-1);
    }
    return fitness;
  } // fitnessEvaluation
 /**
  * Scale the field by beta-gamma to preserve the magnet's influence on the beam.
  *
  * @param kineticEnergy
  * @param designKineticEnergy
  * @param restEnergy
  */
 public void preserveDesignInfluence(
     final double kineticEnergy, final double designKineticEnergy, final double restEnergy) {
   final double energy = kineticEnergy + restEnergy;
   final double designEnergy = designKineticEnergy + restEnergy;
   final double betaGamma = Math.sqrt(Math.pow(energy / restEnergy, 2) - 1.0);
   final double designBetaGamma = Math.sqrt(Math.pow(designEnergy / restEnergy, 2) - 1.0);
   final LiveParameter fieldParameter = getLiveParameter(FIELD_INDEX);
   final double designField = fieldParameter.getDesignValue();
   fieldParameter.setCustomValue(designField * betaGamma / designBetaGamma);
 }
 public YIntervalSeries getYIntervalSeries(String rowname, long factor) {
   YIntervalSeries mydataset = new YIntervalSeries(rowname);
   double sdcount = 0;
   double total = 0;
   Vector<Double> totalvalues = new Vector<Double>();
   double avgtotal = 0;
   double minus = 0;
   double plus = 0;
   double zero = 0;
   for (Integer key : ysum.keySet()) {
     Double value = ysum.get(key) / (double) count.get(key);
     Double point = (double) xsum.get(key) / (double) count.get(key);
     Vector<Double> listofvalues = values.get(key);
     double sumofdiff = 0.0;
     for (Double onevalue : listofvalues) {
       sumofdiff += Math.pow(onevalue - value, 2);
       sdcount++;
       total += Math.pow(onevalue, 2);
       avgtotal += onevalue;
       totalvalues.add(onevalue);
       if (onevalue == 1) {
         plus++;
       }
       ;
       if (onevalue == -1) {
         minus++;
       }
       ;
       if (onevalue == 0) {
         zero++;
       }
       ;
     }
     double sd = Math.sqrt(sumofdiff / count.get(key));
     // mydataset.add(point/factor, value,value+sd,value-sd);
     // mydataset.add(point/factor, value,value,value);
     mydataset.add(
         point / factor,
         value,
         value + 1.96 * (sd / Math.sqrt(count.get(key))),
         value - 1.96 * (sd / Math.sqrt(count.get(key))));
   }
   double sdtotal = 0;
   double avgsd = total / sdcount;
   double test = 0;
   for (Double onevalue : totalvalues) {
     sdtotal += Math.pow(Math.pow(onevalue, 2) - (total / sdcount), 2);
     test += onevalue;
   }
   // System.out.println(rowname+" mean square: "+avgsd+"
   // +/-95%:"+1.96*Math.sqrt(sdtotal/sdcount)/Math.sqrt(sdcount));
   // System.out.println("total -1:"+minus+" total +1:"+plus+" zero: "+zero
   // +" total:"+sdcount);
   return mydataset;
 }
  /**
   * Add edges connecting this cell and its 8 (or less) neighbors
   *
   * @param row
   * @param col
   */
  private void addEdges(int row, int col) {
    System.out.println("Adding (" + row + ", " + col + ")");
    // Add weighted edge
    // North
    if (row > 0 && g.containsVertex(cellContainer[row][col])) {
      g.addEdge(cellContainer[row][col], cellContainer[row - 1][col]);
      g.setEdgeWeight(g.getEdge(cellContainer[row][col], cellContainer[row - 1][col]), 1);
      // NE
      if (col < colCount - 1 && g.containsVertex(cellContainer[row - 1][col + 1])) {
        g.addEdge(cellContainer[row][col], cellContainer[row - 1][col + 1]);
        g.setEdgeWeight(
            g.getEdge(cellContainer[row][col], cellContainer[row - 1][col + 1]), Math.sqrt(2.0));
      }
    }

    // East
    if (col < colCount - 1 && g.containsVertex(cellContainer[row][col + 1])) {
      g.addEdge(cellContainer[row][col], cellContainer[row][col + 1]);
      g.setEdgeWeight(g.getEdge(cellContainer[row][col], cellContainer[row][col + 1]), 1);

      // SE
      if (row < rowCount - 1 && g.containsVertex(cellContainer[row + 1][col + 1])) {
        g.addEdge(cellContainer[row][col], cellContainer[row + 1][col + 1]);
        g.setEdgeWeight(
            g.getEdge(cellContainer[row][col], cellContainer[row + 1][col + 1]), Math.sqrt(2.0));
      }
    }

    // South
    if (row < rowCount - 1 && g.containsVertex(cellContainer[row + 1][col])) {
      g.addEdge(cellContainer[row][col], cellContainer[row + 1][col]);
      g.setEdgeWeight(g.getEdge(cellContainer[row][col], cellContainer[row + 1][col]), 1);

      // SW
      if (col > 0 && g.containsVertex(cellContainer[row + 1][col - 1])) {
        g.addEdge(cellContainer[row][col], cellContainer[row + 1][col - 1]);
        g.setEdgeWeight(
            g.getEdge(cellContainer[row][col], cellContainer[row + 1][col - 1]), Math.sqrt(2.0));
      }
    }

    // West
    if (col > 0 && g.containsVertex(cellContainer[row][col - 1])) {
      g.addEdge(cellContainer[row][col], cellContainer[row][col - 1]);
      g.setEdgeWeight(g.getEdge(cellContainer[row][col], cellContainer[row][col - 1]), 1);

      // NW
      if (row > 0 && g.containsVertex(cellContainer[row - 1][col - 1])) {
        g.addEdge(cellContainer[row][col], cellContainer[row - 1][col - 1]);
        g.setEdgeWeight(
            g.getEdge(cellContainer[row][col], cellContainer[row - 1][col - 1]), Math.sqrt(2.0));
      }
    }
  }
Beispiel #15
0
  static int getNext(int[] mas) {

    int next = 0;
    int n = mas.length;
    int rez = 1, d1 = 0, d2 = 0;

    while (rez == 1) {
      for (int i = 2; i < n; i++) {
        d1 = (mas[i] - mas[i - 1]);
        d2 = (mas[i - 1] - mas[i - 2]);
        rez *= (d1 == d2) ? rez : 0;
      }

      if (rez == 1) {
        next = mas[n - 1] + d1;
        break;
      }

      rez = 1;
      for (int i = 2; i < n; i++) {
        d1 = (int) (1000000 * ((double) mas[i] / (double) mas[i - 1]));
        d2 = (int) (1000000 * ((double) mas[i - 1] / (double) mas[i - 2]));
        rez *= (d1 == d2) ? rez : 0;
      }
      if (rez == 1) {
        next = mas[n - 1] * d1 / 1000000;
        break;
      }
      rez = 1;
      for (int i = 2; i < n; i++) {
        d1 = (int) Math.round(1000000 * (Math.sqrt(mas[i]) - Math.sqrt(mas[i - 1])));
        d2 = (int) Math.round(1000000 * (Math.sqrt(mas[i - 1]) - Math.sqrt(mas[i - 2])));
        rez *= (d1 == d2) ? rez : 0;
      }
      if (rez == 1) {
        next = (int) Math.pow(Math.sqrt(mas[n - 1]) + d1 / 1000000, 2);
        break;
      }
      rez = 1;
      for (int i = 2; i < n; i++) {
        d1 = (int) Math.round(1000000 * (Math.pow(mas[i], 1 / 3.) - Math.pow(mas[i - 1], 1 / 3.)));
        d2 =
            (int)
                Math.round(1000000 * (Math.pow(mas[i - 1], 1 / 3.) - Math.pow(mas[i - 2], 1 / 3.)));
        rez *= (d1 == d2) ? rez : 0;
      }
      if (rez == 1) {
        next = (int) Math.pow(Math.round(Math.pow(mas[n - 1], 1 / 3.)) + d1 / 1000000, 3);
        break;
      }
    }
    return next;
  }
Beispiel #16
0
 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();
 }
Beispiel #17
0
  public static void main(String[] args) throws IOException {
    // Use BufferedReader rather than RandomAccessFile; it's much faster
    BufferedReader f = new BufferedReader(new FileReader("dinner.in"));
    // input file name goes above
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dinner.out")));
    // Use StringTokenizer vs. readLine/split -- lots faster
    StringTokenizer st = new StringTokenizer(f.readLine());
    // Get line, break into tokens
    int i1 = Integer.parseInt(st.nextToken()); // first integer
    int i2 = Integer.parseInt(st.nextToken()); // second integer
    int[] abscissas = new int[i1];
    int[] ordinates = new int[i1];
    for (int i = 0; i < i1; i++) {
      st = new StringTokenizer(f.readLine());
      if (st.hasMoreTokens()) {
        abscissas[i] = Integer.parseInt(st.nextToken());
        ordinates[i] = Integer.parseInt(st.nextToken());
      }
    }
    for (int i = 0; i < i2; i++) {
      st = new StringTokenizer(f.readLine());
      if (st.hasMoreTokens()) {
        int temp1 = Integer.parseInt(st.nextToken());
        int temp2 = Integer.parseInt(st.nextToken());
        double minDist = Integer.MAX_VALUE;
        int mark = 0;
        for (int x = 0; x < i1; x++) {
          if (minDist
              > Math.sqrt(
                  (abscissas[x] - temp1) * (abscissas[x] - temp1)
                      + (ordinates[x] - temp2) * (ordinates[x] - temp2))) {
            minDist =
                Math.sqrt(
                    (abscissas[x] - temp1) * (abscissas[x] - temp1)
                        + (ordinates[x] - temp2) * (ordinates[x] - temp2));
            mark = x;
          }
        }
        abscissas[mark] = 1000001;
        ordinates[mark] = 1000001;
      }
    }

    for (int i = 0; i < i1; i++) {
      if (abscissas[i] != 1000001) {

        System.out.println(i + 1);
      }
    }
    out.close(); // close the output file
    System.exit(0); // don't omit this!
  }
Beispiel #18
0
 private void write_xvg_mean_sd(
     float fc, int r, float[][] arr1, float[][] arr2, float[][] box, String output) {
   // The mean and standard deviation for this method was tested and validated with calculations in
   // R.
   int nOxygen = r / 3;
   float[][] del = new float[nOxygen][3];
   float stdvX, stdvY, stdvZ;
   stdvX = stdvY = stdvZ = 0;
   int i, j;
   for (i = 0; i < nOxygen; i++) {
     del[i][0] = arr2[i * 3][0] - arr1[i * 3][0];
     del[i][1] = arr2[i * 3][1] - arr1[i * 3][1];
     del[i][2] = arr2[i * 3][2] - arr1[i * 3][2];
     if (output.equals("crd")) {
       for (j = 0; j < 3; j++) {
         if ((del[i][j] < 0) && (del[i][j] < (-1 * box[j][j] / 2))) {
           del[i][j] = del[i][j] + box[j][j];
         } else if ((del[i][j] > 0) && (del[i][j] > (box[j][j] / 2))) {
           del[i][j] = del[i][j] - box[j][j];
         }
       }
     }
     sumX = sumX + (del[i][0]);
     sumY = sumY + (del[i][1]);
     sumZ = sumZ + (del[i][2]);
   }
   sumX /= nOxygen;
   sumY /= nOxygen;
   sumZ /= nOxygen;
   for (i = 0; i < nOxygen; i++) {
     stdvX = stdvX + ((del[i][0] - sumX) * (del[i][0] - sumX));
     stdvY = stdvY + ((del[i][1] - sumY) * (del[i][1] - sumY));
     stdvZ = stdvZ + ((del[i][2] - sumZ) * (del[i][2] - sumZ));
   }
   stdvX = (float) Math.sqrt(stdvX / (nOxygen - 1));
   stdvY = (float) Math.sqrt(stdvY / (nOxygen - 1));
   stdvZ = (float) Math.sqrt(stdvZ / (nOxygen - 1));
   if (output.equals("crd")) {
     doutC.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   } else if (output.equals("vel")) {
     doutV.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   } else if (output.equals("frc")) {
     doutF.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   }
 }
Beispiel #19
0
  /*
   * 计算两个字符串(英文字符)的相似度,简单的余弦计算,未添权重
   */
  public static double getSimilarDegree(String str1, String str2) {
    // 创建向量空间模型,使用map实现,主键为词项,值为长度为2的数组,存放着对应词项在字符串中的出现次数
    Map<String, int[]> vectorSpace = new HashMap<String, int[]>();
    int[] itemCountArray = null; // 为了避免频繁产生局部变量,所以将itemCountArray声明在此

    // 以空格为分隔符,分解字符串
    String strArray[] = str1.split(" ");
    for (int i = 0; i < strArray.length; ++i) {
      if (vectorSpace.containsKey(strArray[i])) ++(vectorSpace.get(strArray[i])[0]);
      else {
        itemCountArray = new int[2];
        itemCountArray[0] = 1;
        itemCountArray[1] = 0;
        vectorSpace.put(strArray[i], itemCountArray);
      }
    }

    strArray = str2.split(" ");
    for (int i = 0; i < strArray.length; ++i) {
      if (vectorSpace.containsKey(strArray[i])) ++(vectorSpace.get(strArray[i])[1]);
      else {
        itemCountArray = new int[2];
        itemCountArray[0] = 0;
        itemCountArray[1] = 1;
        vectorSpace.put(strArray[i], itemCountArray);
      }
    }

    // 计算相似度
    double vector1Modulo = 0.00; // 向量1的模
    double vector2Modulo = 0.00; // 向量2的模
    double vectorProduct = 0.00; // 向量积
    Iterator iter = vectorSpace.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      itemCountArray = (int[]) entry.getValue();

      vector1Modulo += itemCountArray[0] * itemCountArray[0];
      vector2Modulo += itemCountArray[1] * itemCountArray[1];

      vectorProduct += itemCountArray[0] * itemCountArray[1];
    }

    vector1Modulo = Math.sqrt(vector1Modulo);
    vector2Modulo = Math.sqrt(vector2Modulo);

    // 返回相似度
    return (vectorProduct / (vector1Modulo * vector2Modulo));
  }
 /**
  * @author Bogdan Sliptsov
  *     <p>Calculates the distance in km between two lat/long points using the haversine formula
  */
 public double distanceGPS(double lat1, double lng1, double lat2, double lng2) {
   int r = 6371; // average radius of the Earth in km
   double dLat = Math.toRadians(lat2 - lat1);
   double dLon = Math.toRadians(lng2 - lng1);
   double a =
       Math.sin(dLat / 2) * Math.sin(dLat / 2)
           + Math.cos(Math.toRadians(lat1))
               * Math.cos(Math.toRadians(lat2))
               * Math.sin(dLon / 2)
               * Math.sin(dLon / 2);
   double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
   double d = r * c;
   return d;
 }
Beispiel #21
0
  // For now the final output is unusable.  The associated quantization step
  // needs some tweaking.  If you get this part working, please let me know.
  public double[][] forwardDCTExtreme(float[][] input) {
    double[][] output = new double[N][N];
    double tmp0;
    double tmp1;
    double tmp2;
    double tmp3;
    double tmp4;
    double tmp5;
    double tmp6;
    double tmp7;
    double tmp10;
    double tmp11;
    double tmp12;
    double tmp13;
    double z1;
    double z2;
    double z3;
    double z4;
    double z5;
    double z11;
    double z13;
    int i;
    int j;
    int v;
    int u;
    int x;
    int y;

    for (v = 0; v < 8; v++) {
      for (u = 0; u < 8; u++) {
        for (x = 0; x < 8; x++) {
          for (y = 0; y < 8; y++) {
            output[v][u] +=
                (((double) input[x][y])
                    * Math.cos(((double) ((2 * x) + 1) * (double) u * Math.PI) / (double) 16)
                    * Math.cos(((double) ((2 * y) + 1) * (double) v * Math.PI) / (double) 16));
          }
        }

        output[v][u] *=
            ((double) (0.25)
                * ((u == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0)
                * ((v == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0));
      }
    }

    return output;
  }
Beispiel #22
0
  /**
   * Compute and store statistics required for generating artificial data.
   *
   * @param data training instances
   * @exception Exception if statistics could not be calculated successfully
   */
  protected void computeStats(Instances data) throws Exception {
    int numAttributes = data.numAttributes();
    m_AttributeStats = new Vector(numAttributes); // use to map attributes to their stats

    for (int j = 0; j < numAttributes; j++) {
      if (data.attribute(j).isNominal()) {
        // Compute the probability of occurence of each distinct value
        int[] nomCounts = (data.attributeStats(j)).nominalCounts;
        double[] counts = new double[nomCounts.length];
        if (counts.length < 2)
          throw new Exception("Nominal attribute has less than two distinct values!");
        // Perform Laplace smoothing
        for (int i = 0; i < counts.length; i++) counts[i] = nomCounts[i] + 1;
        Utils.normalize(counts);
        double[] stats = new double[counts.length - 1];
        stats[0] = counts[0];
        // Calculate cumulative probabilities
        for (int i = 1; i < stats.length; i++) stats[i] = stats[i - 1] + counts[i];
        m_AttributeStats.add(j, stats);
      } else if (data.attribute(j).isNumeric()) {
        // Get mean and standard deviation from the training data
        double[] stats = new double[2];
        stats[0] = data.meanOrMode(j);
        stats[1] = Math.sqrt(data.variance(j));
        m_AttributeStats.add(j, stats);
      } else System.err.println("Decorate can only handle numeric and nominal values.");
    }
  }
Beispiel #23
0
  /**
   * Adapts weights in the network given the specification of which values that should appear at the
   * output (target) when the input has been presented. The procedure is known as error
   * backpropagation. This implementation is "online" rather than "batched", that is, the change is
   * not based on the gradient of the global error, merely the local -- pattern-specific -- error.
   *
   * @param x The input values.
   * @param d The desired output values.
   * @param eta The learning rate, always between 0 and 1, typically a small value, e.g. 0.1
   * @return double An error value (the root-mean-squared-error).
   */
  public double train(double[] x, double[] d, double eta) {

    // present the input and calculate the outputs
    feedforward(x);

    // allocate space for errors of individual nodes
    double[] error = new double[y.length];

    // compute the error of output nodes (explicit target is available -- so quite simple)
    // also, calculate the root-mean-squared-error to indicate progress
    double rmse = 0;
    for (int j = 0; j < y.length; j++) {
      double diff = d[j] - y[j];
      error[j] = diff * outputFunctionDerivative(y[j]);
      rmse += diff * diff;
    }
    rmse = Math.sqrt(rmse / y.length);

    // change weights according to errors
    for (int j = 0; j < y.length; j++) {
      for (int i = 0; i < x.length; i++) {
        w[j][i] += error[j] * x[i] * eta;
      }
      bias[j] +=
          error[j] * 1.0
              * eta; // bias can be understood as a weight from a node which is always 1.0.
    }

    return rmse;
  }
Beispiel #24
0
  /** Returns distance between specified coordinates. */
  public static double getDistance(Point origin, Point destination) {
    int x = destination.getx() - origin.getx();
    int y = destination.gety() - origin.gety();
    double distance = Math.sqrt(x * x + y * y);

    return distance;
  }
Beispiel #25
0
  /**
   * The assignInstance method is used to assign the instances to the centroid which is closest to
   * them (By squared Euclidean distance
   */
  private static void assignInstance(double[][] centroids, double[][] instances, KMeansResult res) {
    // for all instances to update centroids
    for (int i = 0; i < instances.length; i++) {
      // assign each instance to its closest centroid (index starts from 0)
      int centerId = -1;

      // initially set the distance of two points to be as big as possible
      // (which in math is regarded as infinite)
      double minDistance = Double.MAX_VALUE;

      // loop over centroids
      for (int j = 0; j < centroids.length; j++) {
        double currDistance = 0;
        // dimension
        for (int k = 0; k < centroids[j].length; k++) {
          currDistance = currDistance + Math.pow(instances[i][k] - centroids[j][k], 2);
        }
        currDistance = Math.sqrt(currDistance);

        if (currDistance < minDistance) {
          // update new distance to min distance
          minDistance = currDistance;
          // update new centroid
          centerId = j;
        }
      }
      res.clusterAssignment[i] = centerId;
    }
  }
Beispiel #26
0
 public static List<Integer> primeNumbers(int n) {
   boolean[] table = new boolean[n + 1];
   // 把3之后的奇数标记为true
   for (int i = 3; i < table.length; i += 2) {
     table[i] = true;
   }
   // n范围内的质数不会超过sqrt(n)个
   int len = (int) Math.sqrt(n);
   for (int i = 3; i <= len; i++) {
     if (table[i]) {
       for (int j = i + i; j < n; j += i) {
         table[j] = false;
       }
     }
   }
   ArrayList<Integer> primeList = new ArrayList<>();
   if (n > 1) {
     primeList.add(2);
     for (int i = 0; i < table.length; i++) {
       if (table[i]) {
         primeList.add(i);
       }
     }
   }
   return primeList;
 }
  /**
   * Calculates the standard deviation statistic
   *
   * @return Standard deviation statistic
   */
  private double getStandardDeviation() {
    if (count <= 1.0D) {
      return 0.0D;
    }

    return Math.sqrt(((count * sumOfSquares) - (sum * sum)) / (count * (count - 1.0D)));
  }
Beispiel #28
0
 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);
 }
Beispiel #29
0
 // Returns the distance between two planets, rounded up to the next highest
 // integer. This is the number of discrete time steps it takes to get
 // between the two planets.
 public int Distance(int sourcePlanet, int destinationPlanet) {
   Planet source = planets.get(sourcePlanet);
   Planet destination = planets.get(destinationPlanet);
   double dx = source.X() - destination.X();
   double dy = source.Y() - destination.Y();
   return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
 }
Beispiel #30
0
  public void calcSigma() {

    Double summation = new Double(0);

    // Take the sum of gdplist and divide by n

    for (Double x1 : gdplist) summation += x1;

    average = summation / gdplist.size();

    // Now we have the mean

    // Take the difference of the GDP by year and the mean
    // Sum all of the squares of the differences
    // Take the square root of the sum == std deviation

    summation = new Double(0);

    for (Double x1 : gdplist) { // look at each year GDP
      Double x2 = x1 - average; // subtract the average from that year GDP

      summation += (x2 * x2); // square the result and add it to a total sum
    }

    summation = summation / gdplist.size();

    stdev = Math.sqrt(summation);
  }