Ejemplo n.º 1
0
 public MerkleTree(Vector<Indexable> v) {
   nodeMap = new HashMap<Integer, MerkleTreeNode>();
   this.store = v;
   int exp = 0;
   while ((int) Math.pow(2, exp) < store.size()) {
     exp++;
   }
   for (int i = store.size(); i < (int) Math.pow(2, exp); i++) {
     store.add(i, null);
   }
   Vector<MerkleTreeNode> hashes = new Vector<MerkleTreeNode>();
   for (int i = 0; i < store.size(); i++) {
     if (store.get(i) != null) {
       MerkleTreeNode temp = new MerkleTreeNode(store.get(i).getBytes(), i);
       nodeMap.put(i, temp);
       hashes.add(temp);
     } else {
       MerkleTreeNode temp = new MerkleTreeNode(i);
       nodeMap.put(i, temp);
       hashes.add(temp);
     }
   }
   while (hashes.size() > 1) {
     Vector<MerkleTreeNode> temp = new Vector<MerkleTreeNode>();
     for (int i = 0; i < hashes.size(); i += 2) {
       temp.add(MerkleTreeNode.combineDigestFactory(hashes.get(i), hashes.get(i + 1)));
     }
     hashes = temp;
   }
   root = hashes.get(0);
 }
 double oblicz_wage(int x1, int y1, int x2, int y2) {
   double x = (double) Math.pow(Math.abs((x1 - x2)), 2);
   double y = (double) Math.pow(Math.abs((y1 - y2)), 2);
   double wynik = Math.sqrt(x + y) * 1000;
   wynik = Math.round(wynik);
   return (wynik / 1000);
 }
Ejemplo n.º 3
0
  /*
   * We completed handling of a filtered block. Update false-positive estimate based
   * on the total number of transactions in the original block.
   *
   * count includes filtered transactions, transactions that were passed in and were relevant
   * and transactions that were false positives (i.e. includes all transactions in the block).
   */
  protected void trackFilteredTransactions(int count) {
    // Track non-false-positives in batch.  Each non-false-positive counts as
    // 0.0 towards the estimate.
    //
    // This is slightly off because we are applying false positive tracking before non-FP tracking,
    // which counts FP as if they came at the beginning of the block.  Assuming uniform FP
    // spread in a block, this will somewhat underestimate the FP rate (5% for 1000 tx block).
    double alphaDecay = Math.pow(1 - FP_ESTIMATOR_ALPHA, count);

    // new_rate = alpha_decay * new_rate
    falsePositiveRate = alphaDecay * falsePositiveRate;

    double betaDecay = Math.pow(1 - FP_ESTIMATOR_BETA, count);

    // trend = beta * (new_rate - old_rate) + beta_decay * trend
    falsePositiveTrend =
        FP_ESTIMATOR_BETA * count * (falsePositiveRate - previousFalsePositiveRate)
            + betaDecay * falsePositiveTrend;

    // new_rate += alpha_decay * trend
    falsePositiveRate += alphaDecay * falsePositiveTrend;

    // Stash new_rate in old_rate
    previousFalsePositiveRate = falsePositiveRate;
  }
Ejemplo n.º 4
0
  private long computeDsh3(double q) {
    double t1num = 0.0;
    double t1den = 0.0;
    double t2num = 0.0;
    double t2den = 0.0;

    double qsq = q * q;
    double _1qsq = 1.0 - qsq;
    double _1q = 1.0 - q;
    double _q1 = 1.0 + q;

    for (long i = 1; i <= n; i++) {
      double fi = (double) f.get(i);

      double id = (double) i;

      double _1qi = Math.pow(_1q, id);

      double id_1 = (double) (i - 1);

      t1num += id * qsq * Math.pow(_1qsq, id_1) * fi;

      t1den += _1qi * (Math.pow(_q1, id) - 1.0) * fi;

      t2num += _1qi * fi;

      t2den += id * q * Math.pow(_1q, id_1) * fi;
    }

    double f1 = (double) (f.get(1));

    double D = (double) dn + (f1 * (t1num / t1den) * ((t2num / t2den) * (t2num / t2den)));

    return Math.round(D);
  }
Ejemplo n.º 5
0
  public static int gainKillExperience(Thing h, Thing t) {
    int hlevel = h.getLevel();
    int tlevel = t.getLevel();

    int killcount = 0;
    if (h.isHero()) {
      killcount = incKillCount(t);
      if (killcount == 1) {
        Score.scoreFirstKill(t);
      }
    }

    int base = t.getStat("XPValue");
    double xp = base;
    xp = xp * Math.pow(experienceDecay, killcount);
    xp = xp * Math.pow(experienceLevelMultiplier, tlevel - 1);

    // decrease xp gain for killing lower level monsters
    if (hlevel > tlevel) xp = xp / (hlevel - tlevel);

    int gain = (int) xp;

    Hero.gainExperience(gain);
    return gain;
  }
Ejemplo n.º 6
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);
 }
 /**
  * Computes and plots correlation functions
  *
  * @param tauMax is the maximum time for correlation functions
  */
 public void computeCorrelation(int tauMax) {
   plotFrame.clearData();
   double energyAccumulator = 0, magnetizationAccumulator = 0;
   double energySquaredAccumulator = 0, magnetizationSquaredAccumulator = 0;
   for (int t = 0; t < numberOfPoints; t++) {
     energyAccumulator += energy[t];
     magnetizationAccumulator += magnetization[t];
     energySquaredAccumulator += energy[t] * energy[t];
     magnetizationSquaredAccumulator += magnetization[t] * magnetization[t];
   }
   double averageEnergySquared = Math.pow(energyAccumulator / numberOfPoints, 2);
   double averageMagnetizationSquared = Math.pow(magnetizationAccumulator / numberOfPoints, 2);
   // compute normalization factors
   double normE = (energySquaredAccumulator / numberOfPoints) - averageEnergySquared;
   double normM = (magnetizationSquaredAccumulator / numberOfPoints) - averageMagnetizationSquared;
   for (int tau = 1; tau <= tauMax; tau++) {
     double c_MAccumulator = 0;
     double c_EAccumulator = 0;
     int counter = 0;
     for (int t = 0; t < numberOfPoints - tau; t++) {
       c_MAccumulator += magnetization[t] * magnetization[t + tau];
       c_EAccumulator += energy[t] * energy[t + tau];
       counter++;
     }
     // correlation function defined so that c(0) = 1 and c(infinity) -> 0
     plotFrame.append(0, tau, ((c_MAccumulator / counter) - averageMagnetizationSquared) / normM);
     plotFrame.append(1, tau, ((c_EAccumulator / counter) - averageEnergySquared) / normE);
   }
   plotFrame.setVisible(true);
 }
Ejemplo n.º 8
0
 /** @return distance from this location to location with x and y coordinations */
 public double getLength(double[] coordinations) {
   double storage = Math.pow(coordinations[0] - this.coordinations[0], 2);
   for (int i = 1; i < coordinations.length; i++) {
     storage += Math.pow(coordinations[i] - this.coordinations[i], 2);
   }
   return Math.sqrt(storage);
 }
Ejemplo n.º 9
0
 public double getLength(List<Double> coordinations) {
   double storage = Math.pow(coordinations.get(0) - this.coordinations[0], 2);
   for (int i = 1; i < coordinations.size(); i++) {
     storage += Math.pow(coordinations.get(i) - this.coordinations[i], 2);
   }
   return Math.sqrt(storage);
 }
Ejemplo n.º 10
0
 public double nextDouble() {
   int c = read();
   while (isSpaceChar(c)) c = read();
   int sgn = 1;
   if (c == '-') {
     sgn = -1;
     c = read();
   }
   double res = 0;
   while (!isSpaceChar(c) && c != '.') {
     if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
     if (c < '0' || c > '9') throw new InputMismatchException();
     res *= 10;
     res += c - '0';
     c = read();
   }
   if (c == '.') {
     c = read();
     double m = 1;
     while (!isSpaceChar(c)) {
       if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
       if (c < '0' || c > '9') throw new InputMismatchException();
       m /= 10;
       res += (c - '0') * m;
       c = read();
     }
   }
   return res * sgn;
 }
Ejemplo n.º 11
0
  public void calc() {
    System.out.println("Please Input tow primes:");
    Scanner sc = new Scanner(System.in);
    int p = sc.nextInt();
    int q = sc.nextInt();
    int n = p * q;
    int s = (p - 1) * (q - 1);
    int e, d;
    for (e = 2; e < s; ++e) if (gcd(e, s) == 1) break;

    e = 31;
    for (d = 2; ; ++d) if (d * e % s == 1) break;

    System.out.println("p\tq\tn\ts\te\td");

    System.out.printf("%d\t%d\t%d\t%d\t%d\t%d\n", p, q, n, s, e, d);

    System.out.println("Please Input M:");

    int m = sc.nextInt();

    long c = Math.round(Math.pow(m, e)) % n;

    long mm = Math.round(Math.pow(c, d)) % n;

    System.out.printf("After encrypt: %d\n", c);

    System.out.printf("After decrypt: %d\n", mm);
  }
Ejemplo n.º 12
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)));
  }
Ejemplo n.º 13
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));
 }
Ejemplo n.º 14
0
 /**
  * Fisher distribution
  *
  * @param f Fisher value
  * @param n1 N1 value
  * @param n2 N2 value
  * @return P-value associated
  */
 private static double FishF(double f, int n1, int n2) {
   double x = n2 / (n1 * f + n2);
   if ((n1 % 2) == 0) {
     return StatCom(1 - x, n2, n1 + n2 - 4, n2 - 2) * Math.pow(x, n2 / 2.0);
   }
   if ((n2 % 2) == 0) {
     return 1 - StatCom(x, n1, n1 + n2 - 4, n1 - 2) * Math.pow(1 - x, n1 / 2.0);
   }
   double th = Math.atan(Math.sqrt(n1 * f / (1.0 * n2)));
   double a = th / (Math.PI / 2.0);
   double sth = Math.sin(th);
   double cth = Math.cos(th);
   if (n2 > 1) {
     a = a + sth * cth * StatCom(cth * cth, 2, n2 - 3, -1) / (Math.PI / 2.0);
   }
   if (n1 == 1) {
     return 1 - a;
   }
   double c =
       4 * StatCom(sth * sth, n2 + 1, n1 + n2 - 4, n2 - 2) * sth * Math.pow(cth, n2) / Math.PI;
   if (n2 == 1) {
     return 1 - a + c / 2.0;
   }
   int k = 2;
   while (k <= (n2 - 1) / 2.0) {
     c = c * k / (k - .5);
     k = k + 1;
   }
   return 1 - a + c;
 }
Ejemplo n.º 15
0
  public void findTHS() {
    int doubleRange = this.range * 2;

    for (int i = 0; i < numNodes; i++) {
      Node active = nodes.get(i);
      for (int j = 0; j < numNodes; j++) {
        Node toCheck = nodes.get(j);
        if (i != j) {
          // System.out.println("active x: " + active.getXLanePosition() + " active y: " +
          // active.getyLanePosition());
          // System.out.println("check  y : " + toCheck.getXLanePosition() + " check y:  " +
          // toCheck.getyLanePosition());
          int activeX = active.getXLanePosition();
          int activeY = active.getyLanePosition();

          int checkX = toCheck.getXLanePosition();
          int checkY = toCheck.getyLanePosition();

          double distance =
              Math.sqrt(Math.pow((activeX - checkX), 2) + Math.pow((activeY - checkY), 2));
          if (distance <= doubleRange) {
            active.addToTHS(toCheck.getID());
          }
        }
      }
    }
  }
Ejemplo n.º 16
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
  }
Ejemplo n.º 17
0
  // evaluate Fisher score of all indexes in current ^ featIndex
  private double evaluateFisher(HashSet<Integer> current, int featIndex) {
    ArrayList<Integer> d = new ArrayList<Integer>(current);
    d.add(featIndex);
    ArrayList<ArrayList<Integer>> vectors = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i < getA().get_classes().size(); i++) {
      ArrayList<ArrayList<Integer>> cl = getA().features.get(getA().get_classes().get(i));
      ArrayList<Integer> tmp = new ArrayList<Integer>();
      for (int j = 0; j < cl.size(); j++) {
        int sum = 0;
        for (int k = 0; k < d.size(); k++) sum += cl.get(j).get(d.get(k));
        if (sum == d.size()) tmp.add(1);
        else tmp.add(0);
      }
      vectors.add(tmp);
    }
    ArrayList<double[]> stats = new ArrayList<double[]>();
    int count = 0;
    double sum = 0.0;
    for (int i = 0; i < vectors.size(); i++) {
      double[] res = computeMeanVariance(vectors.get(i));
      sum += (vectors.get(i).size() * res[0]);
      count += vectors.get(i).size();
      stats.add(res);
    }
    sum = sum / count;

    double num = 0.0;
    double denom = 0.0;
    for (int i = 0; i < stats.size(); i++) {
      num += (vectors.get(i).size() * Math.pow(stats.get(i)[0] - sum, 2));
      denom += (vectors.get(i).size() * Math.pow(stats.get(i)[1], 2));
    }
    if (denom == 0.0) return 0;
    else return num / denom;
  }
Ejemplo n.º 18
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;

        }
        //  }
      }
    }
  }
 private static int adjust(int expectedOnMyMachine, long thisTiming, long ethanolTiming) {
   // most of our algorithms are quadratic. sad but true.
   double speed = 1.0 * thisTiming / ethanolTiming;
   double delta = speed < 1 ? 0.9 + Math.pow(speed - 0.7, 2) : 0.45 + Math.pow(speed - 0.25, 2);
   expectedOnMyMachine *= delta;
   return expectedOnMyMachine;
 }
Ejemplo n.º 20
0
 public static Counter ConstrainedEig(SparseMatrix mat, SparseMatrix orthogMat) {
   double trimEps = 0;
   int iterLimit = 10000;
   long start;
   long end;
   Counter vector = new Counter();
   int vecLen = mat.colDim;
   for (int i = 0; i < vecLen; i++) {
     //			vector.add(i, 1.0/Math.sqrt(vecLen));
     vector.add(i, Math.random() - 0.5);
   }
   Counter oldVector = new Counter();
   //		vector = mat.multiply(vector);
   //		for(int r: orthogMat.rows){
   //			Counter orthogRow = orthogMat.getRow(r);
   //			vector.orthogonalize(orthogRow);
   ////			System.out.println(vector.dot(orthogRow));
   //		}
   double norm = 0;
   double sim = 0;
   double diff = 1.0;
   double diffNeg = 1.0;
   int t = 0;
   start = System.currentTimeMillis();
   while (diff > Math.pow(10.0, -16.0) && diffNeg > Math.pow(10.0, -16.0) && t < iterLimit) {
     t += 1;
     //			vector.trimKeys(trimEps);
     oldVector = new Counter(vector);
     vector = mat.multiply(vector);
     for (int r : orthogMat.rows) {
       Counter orthogRow = orthogMat.getRow(r);
       //				System.out.println("before: "+vector.dot(orthogRow));
       vector.orthogonalize(orthogRow);
       //				System.out.println("after: "+vector.dot(orthogRow));
     }
     norm = 0;
     norm = vector.norm();
     vector.multiply(1.0 / norm);
     diff = 0;
     diffNeg = 0;
     Set<Integer> vecOldUnion = vector.concreteKeySet();
     vecOldUnion.addAll(oldVector.concreteKeySet());
     for (int i : vecOldUnion) {
       //			for(int i = 0; i < mat.colDim; i++){
       diff += (oldVector.get(i) - vector.get(i)) * (oldVector.get(i) - vector.get(i));
       diffNeg += (oldVector.get(i) + vector.get(i)) * (oldVector.get(i) + vector.get(i));
     }
     sim = vector.dot(oldVector);
     //			System.out.println(diff+" "+diffNeg+" "+sim+" "+norm+"
     // "+vector.dot(orthogMat.getRow(0)));
     //			System.out.println(vector.toString());
     // System.out.println(oldVector.toString());
   }
   System.out.println(norm + " " + orthogMat.rows.size() + " " + sim);
   //		System.out.println(mat.toStringValues());
   end = System.currentTimeMillis();
   System.out.println("Time: " + (end - start) + " iterations: " + t);
   return vector;
 }
 int integerBreak(int n) {
   if (n == 2 || n == 3) return n - 1;
   int div = n / 3;
   int reminder = n % 3;
   if (reminder == 1) return (int) Math.pow(3, div - 1) * 4;
   else if (reminder == 0) return (int) Math.pow(3, div);
   return (int) Math.pow(3, div) * 2;
 }
Ejemplo n.º 22
0
  static int distance(int[] pointA, int[] pointB) {

    return (int)
        Math.ceil( //
            Math.sqrt( //
                (Math.pow(pointB[0] - pointA[0], 2) //
                    + Math.pow(pointB[1] - pointA[1], 2))));
  }
Ejemplo n.º 23
0
    protected static double Distance(List<Double> p1, List<Double> p2) {
      double sumOfSquaredDifferences = 0.0;

      for (int i = 0; i < p1.size(); i++) {
        sumOfSquaredDifferences += Math.pow(p1.get(i) - p2.get(i), 2.0);
      }

      return Math.pow(sumOfSquaredDifferences, 0.5);
    }
Ejemplo n.º 24
0
 /**
  * Find the distance between two characters
  *
  * @param Targ Target character
  * @return distance
  */
 public double Dist(GameObject Targ) {
   // find x squared and y squared
   double dx =
       Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2);
   double dy =
       Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2);
   // find distance
   return (Math.sqrt(dx + dy));
 }
Ejemplo n.º 25
0
 /** Computes the power for each of the Spectrogram.SAMPLE_SIZE/2 frequency bins. */
 private void computePower() {
   for (int i = 0; i < Spectrogram.SAMPLE_SIZE; i += 2) {
     double ai = Math.pow(transformedSamples[i], 2);
     double bi = Math.pow(transformedSamples[i + 1], 2);
     double power = ai + bi;
     power = Math.sqrt(power);
     freqPower[i / 2] = power;
   }
 }
Ejemplo n.º 26
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);
        }
      }
Ejemplo n.º 27
0
 public int trailingZeroes(int n) {
   int sum = 0;
   int count = 1;
   while ((n / Math.pow(5, count)) >= 1) {
     sum = sum + n / (int) Math.pow(5, count);
     count = count + 1;
   }
   return sum;
 }
Ejemplo n.º 28
0
  /**
   * 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;
  }
Ejemplo n.º 29
0
  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
Ejemplo n.º 30
0
  public static void main(String[] args) throws Throwable {
    double begin = System.currentTimeMillis();
    /*File file = new File(args[0]);
    BufferedReader buffer = new BufferedReader(new FileReader(file));
    String line;
    while ((line = buffer.readLine()) != null) {
        int digits = Integer.parseInt(line);
        */
    int digits = 10;
    int count = 1;
    int iterations = 0;
    int limit = (int) Math.pow((double) 10, (double) digits);
    // start at the first lucky number besides 0 for 6 digits: 0 0 1 | 0 0 1
    int start = (int) Math.pow((double) 10, (double) (digits / 2));
    System.out.println("start: " + start + " and limit: " + limit);
    for (int i = start + 1; i < limit; i++) {
      iterations++;
      int current = i;
      int[] number = new int[digits];
      int len = number.length;

      int index = len - 1;
      // populate array with values
      while (current > 0) {
        number[index] = current % 10;
        current /= 10;
        index--;
      }

      if (!sidesEqual(number)) continue;
      // percentage of "hits" is very small. this way it only runs the sidesEqual method once
      // instead of twice
      /*
       * Step 2: Test that each side is equal. If they are, and the last digit is 0, proceed normally
       */
      else if (sidesEqual(number) && number[len - 1] == 0) {
        // System.out.println("sides match and last digit 0");
        count++;
      }

      /*
       * Step 2b: If both sides match but the last digit is NOT ZERO,
       * then the next occurance (if it exists) will be exactly 9 numbers after the current i
       */

      else if (sidesEqual(number)) {
        // System.out.println("Sides match, last digit is not zero");
        count++;
        i += 8; // (8 since 1 will be added at the end of this iteration or for loop)
      }
    } // end for loop

    System.out.println("count: " + count + " and iterations: " + iterations);
    // } //end while
    System.out.println("runtime in seconds: " + (System.currentTimeMillis() - begin) / 1000);
  } // end main method