Ejemplo n.º 1
1
    public void applyForce() {
      // force is proportional to the diff between restLen and current idst

      // a vector from A --> B
      Vector diff = new Vector(endA.pos, endB.pos);

      // compute the current distance
      float dist = diff.getMagnitude();
      // compute dx, which is what the force depends on
      float dx = Math.abs(dist - restLen);

      // a vector containing just the direction component of A --> B
      Vector dir = diff.copy().normalize();

      Vector force = dir.copy().scale(-K * dx, -K * dx);

      if (restLen < getDistance()) {
        // forces go INWARDS

        endB.addForce(force);
        endA.addForce(force.reverse());
      } else {
        // forces go OUTWARDS

        endA.addForce(force);
        endB.addForce(force.reverse());
      }
    }
Ejemplo n.º 2
0
  /**
   * A dirty hacking method for getting rid of any imprecision errors in the floating point
   * representation of the given double value. As it is the {@link AffineTransform} creates lots of
   * these imprecision errors, resulting in the Math.floor/round/ceil functions being of by one more
   * often than you think!!!
   *
   * @param value to clean
   * @return the cleaned value.
   */
  private final double removeImprecisions(double value) {
    // quick and dirty, a 0 will always be a 0 (yes it sometimes happens).
    if (value == 0) {
      return value;
    }

    // check if no 'extra' values are given (e.g. 25.6).
    double result = Math.abs((value * DECIMAL_ACCURACY) - (Math.round(value * DECIMAL_ACCURACY)));
    if (result == 0) {
      // a perfect match, don't do any rounding e.g 25.6
      return value;
    }
    // check the decimal value against the delta (which depends on the resolution).
    result = (value - Math.floor(value)) * delta;
    if (Math.abs(result) < delta) {
      // almost 0, so round it up eg. 25.600000008, but not in sight an ulp
      return Math.round(value * DECIMAL_ACCURACY) * INV_DECIMAL_ACCURACY;
    }
    // test if we are in reach of an ulp
    result = value;
    double nextup = Math.nextUp(value);
    double nextdown = Math.nextAfter(value, Double.NEGATIVE_INFINITY);

    double upRest = ((nextup * DECIMAL_ACCURACY) - Math.floor(nextup * DECIMAL_ACCURACY));
    double downRest = (nextdown * DECIMAL_ACCURACY - Math.floor(nextdown * DECIMAL_ACCURACY));
    upRest -= Math.floor(upRest);
    downRest -= Math.floor(downRest);
    if (upRest == 0) {
      // 0 only if the result was of by an ulp
      result = nextup;
    } else if (downRest == 0) {
      result = nextdown;
    }
    return result;
  }
Ejemplo n.º 3
0
  @Override
  public void onClick(View v) {
    if ((Math.abs(freeX - myX) == 1 && freeY == myY)
        || (Math.abs(freeY - myY) == 1 && freeX == myX)) {
      exchange(myX, myY);

      myActivity
          .getResult()
          .setText(String.valueOf(Integer.parseInt((String) myActivity.getResult().getText()) + 1));

      if (freeY == DIMENSION - 1 && freeX == DIMENSION - 1) {
        boolean isSorted = true;
        for (int i = 0; i < DIMENSION * DIMENSION - 1; ++i) {
          if (!((Button) myAdapter.getItem(i)).getText().equals(String.valueOf(i + 1))) {
            isSorted = false;
            break;
          }
        }
        if (isSorted) {
          Intent intent = new Intent(myActivity, GiveName.class);
          myActivity.startActivityForResult(intent, 1);
        }
      }
    }
  }
Ejemplo n.º 4
0
  // 檢查其子節點並做符號的標示
  public static String checkChild(int[][] tmp, int i, int j, int N, int T, int counter) {
    int testtest = 0;
    String test = "";

    // first & child checking
    // check if they are greater than T
    if ((Math.abs(tmp[2 * i][j * 2]) < T)
        && (Math.abs(tmp[2 * i + 1][j * 2]) < T)
        && (Math.abs(tmp[2 * i][j * 2 + 1]) < T)
        && (Math.abs(tmp[2 * i + 1][j * 2 + 1]) < T)) {
      if (counter == 1) {
        i = 2 * i;
        j = 2 * j;
        for (int r = 0; r < 4; r++) {
          for (int s = 0; s < 4; s++) {
            if (Math.abs(tmp[2 * i + r][j * 2 + s]) > T) {
              testtest++;
              // IdxTable[2*i+r][j*2+s] = 1;
            }
            // else IdxTable[2*i+r][j*2+s] = 0;
          }
        }

        if ((testtest == 0) || (counter == 2)) test = "0";
        else test = "1";
      } // end if counter ==1
    } else test = "1";

    return test;
  }
Ejemplo n.º 5
0
  /**
   * Carries out all the calculations based on Newtonian mechanics and updates fields appropriately
   * Time elapsed is in seconds use s = u*t + 0.5*a*t^2 to update object position uses v = u + a*t
   * to update object velocity
   */
  public static void updater(double t, Object object) {

    // Fields
    Point temp = new Point();

    // use s = u*t + 0.5*a*t^2 to update object position

    double tempX = (object.getPosition().getX() + object.getxV() * t);
    double tempY =
        (object.getPosition().getY() + object.getyV() * t + (0.5 * object.getG() * t * t));
    temp.setLocation(tempX, tempY);
    object.setPosition(temp);

    // uses v = u + a*t to update object velocity
    object.setyV(object.getyV() + object.getG() * t);

    // fixes object position and velocity to allow it to bounce on the x  and y axis
    if (object.getPosition().getX() < object.getWidth() / 2) {
      object.setxV(java.lang.Math.abs(object.getxV()));
      temp.setLocation(object.getWidth() / 2, object.getPosition().getY());
      object.setPosition(temp);
    }
    if (object.getPosition().getY() < object.getWidth() / 2) {
      object.setyV(java.lang.Math.abs(object.getyV()));
      temp.setLocation(object.getPosition().getX(), object.getWidth() / 2);
      object.setPosition(temp);
    }
  }
Ejemplo n.º 6
0
  public boolean isWall(int p1, int q1, int p2, int q2) {
    // is there a wall between point a and point b?

    //	First, what is the delta? AKA which direction are we heading?

    int dX = p2 - p1;
    int dY = q2 - q1;
    int i = findIndex(p1, q1);

    if ((java.lang.Math.abs(dY + dX) != 1)
        || (java.lang.Math.abs(dY) > 1)
        || (java.lang.Math.abs(dX) > 1)) {
      throw new Error("impossible move");
    }
    // now that we have a delta, we can convert to index notation (where in the bitstring is it?)
    // then modify due to delta
    else {
      i += dX; // if we have to shift right or left, we just do that
      i += (x * 2 + 1) * dY; // and if we shift up or down, we do so by b steps

      // i is now the index for the boundary between the two points
    }
    // ok now we can look up if there is a wall at i
    if (bits.charAt(i) == '1') {
      return true;
    } else if (bits.charAt(i) == '0') {
      return false;
    } else {
      System.out.println("ERROR. Boundary is neither a 0 nor 1. This should never happen.");
      return true;
    }
  }
Ejemplo n.º 7
0
 public void generateCaverns(int count) {
   for (int i = 0; i < count; i++) {
     m_logger.debug("Generating underground erosion bubbles: " + i + "/" + count);
     int x = m_random.nextInt(m_width);
     int y = m_random.nextInt(m_height);
     int z = m_random.nextInt(m_depth / 4);
     int radius = m_random.nextInt(60) + 40;
     radius = 6;
     int type = m_random.nextInt(100);
     if (type > 90) type = BlockConstants.LAVA;
     else if (type > 45) type = BlockConstants.AIR;
     else type = BlockConstants.WATER;
     for (int m = 0; m < 2; m++) {
       BUBBLE_GEN:
       for (int j = x - radius; j < x + radius * 2; j++) {
         if (j < 0) j = 0;
         if (j >= m_width) break BUBBLE_GEN;
         for (int k = y - radius; k < y + radius * 2; k++) {
           if (k < 0) k = 0;
           if (k >= m_height) break BUBBLE_GEN;
           for (int l = z - radius; l < z + radius; l++) {
             if (l < 0) l = 0;
             if (l >= m_depth) break BUBBLE_GEN;
             double distance =
                 Math.sqrt(Math.pow(j - x, 2) + Math.pow(k - y, 2) + Math.pow(l - z, 2));
             if (Math.abs(distance / radius) <= Math.abs(m_random.nextGaussian())) {
               m_blocks[j][k][l] = (byte) type;
             }
           }
         }
       }
       x++;
     }
   }
 }
Ejemplo n.º 8
0
 public boolean equals(Area a) {
   if (java.lang.Math.abs(topleft.latDec - a.topleft.latDec) < edgeTolerance
       && java.lang.Math.abs(topleft.lonDec - a.topleft.lonDec) < edgeTolerance
       && java.lang.Math.abs(buttomright.latDec - a.buttomright.latDec) < edgeTolerance
       && java.lang.Math.abs(buttomright.lonDec - a.buttomright.lonDec) < edgeTolerance)
     return true;
   else return false;
 }
Ejemplo n.º 9
0
 public void onAccelerationChanged(float x, float y, float z) {
   if (Math.abs(x - mx) > 1.5 || Math.abs(y - my) > 1.5 || Math.abs(z - mz) > 1.5) {
     affirm.start();
   }
   mx = x;
   my = y;
   mz = z;
 }
 public double adjustOutsidePosition(double position, double start, double end) {
   while (position > end) {
     position -= Math.abs(end - start);
   }
   while (position < start) {
     position += Math.abs(end - start);
   }
   return position;
 }
Ejemplo n.º 11
0
 int[] setRunningDirection(int distX, int distY) {
   int[] directions = new int[] {0, 0};
   if (Math.abs(distX) > Math.abs(distY)) {
     directions[0] = (int) Math.signum(distX);
   } else {
     directions[1] = (int) Math.signum(distY);
   }
   return avoidWalls(directions);
 }
Ejemplo n.º 12
0
  private void interpolateLine(int startX, int startY, int destX, int destY) {
    while (startX < 0 || startY < 0 || startX > m_width - 1 || startY > m_height - 1) {
      double direction = Math.atan2(destY - startY, destX - startX);
      startX += ceilInt(Math.cos(direction));
      startY += ceilInt(Math.sin(direction));
    }
    int startHeight = m_contour[startX][startY];
    int endHeight = m_contour[destX][destY];
    if (startHeight == endHeight) return;
    double distance = Math.sqrt(Math.pow(startX - destX, 2) + Math.pow(startY - destY, 2));
    double realX = startX;
    double realY = startY;
    double value = 1;
    while (value > 0) {
      if (Math.abs(destX - realX) < 1.2 && Math.abs(destY - realY) < 1.2) break;

      double direction = Math.atan2(destY - realY, destX - realX);
      value = Math.sqrt(Math.pow(realX - destX, 2) + Math.pow(realY - destY, 2)) / distance;
      double height;

      if (value < 0.5) height = (startHeight - endHeight) / 2 * Math.pow(value * 2, 3) + endHeight;
      else height = (startHeight - endHeight) / 2 * (Math.pow(value * 2 - 2, 3) + 2) + endHeight;

      double dx = Math.cos(direction);
      double dy = Math.sin(direction);
      if (dx == -1 || dx == 1) dy = 0;
      if (dy == -1 || dy == 1) dx = 0;

      realX += ceilInt(dx);
      realY += ceilInt(dy);
      int centerX = ceilInt(realX);
      int centerY = ceilInt(realY);

      double dTopX = Math.cos(direction + Math.PI / 2);
      double dTopY = Math.sin(direction + Math.PI / 2);
      int topX = ceilInt(realX + dTopX);
      int topY = ceilInt(realY + dTopY);

      double dBottomX = Math.cos(direction - Math.PI / 2);
      double dBottomY = Math.sin(direction - Math.PI / 2);
      int bottomX = ceilInt(realX + dBottomX);
      int bottomY = ceilInt(realY + dBottomY);

      if (m_antiAlias) {
        m_contour[centerX][centerY] =
            (int) (Math.sqrt(Math.pow(centerX - realX, 2) + Math.pow(centerY - realY, 2)) * height);
        m_contour[topX][topY] =
            (int) (Math.sqrt(Math.pow(topX - realX, 2) + Math.pow(topY - realY, 2)) * height);
        m_contour[bottomX][bottomY] =
            (int) (Math.sqrt(Math.pow(bottomX - realX, 2) + Math.pow(bottomY - realY, 2)) * height);
      } else {
        m_contour[centerX][centerY] = (int) height;
      }
    }
  }
Ejemplo n.º 13
0
  /// @pre --
  /// @post retorna l'angle que ha d'apuntar la NauEnemiga(e) per aconseguir que un RaigLaser
  // disparat per e
  ///     col·lisioni amb n
  private int angleApuntarMoviment(Nau n) {
    double[] cn = n.obtenirCentreTriangle();
    double[] ce = obtenirCentreTriangle();

    double dist = Math.hypot(Math.abs(cn[0] - ce[0]), Math.abs(cn[1] - ce[1]));
    double temps = dist / velocitatRaig_;
    double[] previsio = preveurePosicio(n, temps);

    double angle = angleApuntar(previsio);
    return (int) angle;
  }
Ejemplo n.º 14
0
 /**
  * Calculate euclidian distance between this node and the given node, rounded to the nearest
  * integer.
  *
  * @param n Other node
  * @return Euclidian distance
  */
 public int calcApproxDistanceTo(Node n) {
   return (int) (Math.abs(n.x - x) + Math.abs(n.y - y));
   /*
   double absxd = Math.abs(n.x-x);
   double absyd = Math.abs(n.y-y);
   double approx1 = Math.max(absxd, absyd);
   double approx2 = INVSQRT2*(absxd+absyd);
   double approx = Math.max(approx1, approx2);
   return (int)Math.round(approx);
   */
 }
Ejemplo n.º 15
0
  public static void main(String[] args) {

    double d1 = -2.55;
    float f2 = (float) 1.5;
    int i1 = -5;
    long l1 = -1000;

    System.out.println("|" + d1 + "| es " + Math.abs(d1));
    System.out.println("|" + f2 + "| es " + Math.abs(f2));
    System.out.println("|" + i1 + "| es " + Math.abs(i1));
    System.out.println("|" + l1 + "| es " + Math.abs(l1));
  }
Ejemplo n.º 16
0
  public void physics() {

    tv = tv + ta;
    rv = rv + ra;

    if (ta == 0) {

      if (tv > 0) {
        tv = tv - tf;
        if (tv < 0) {
          tv = 0;
        }
      }
      if (tv < 0) {
        tv = tv + tf;
        if (tv > 0) {
          tv = 0;
        }
      }
    }

    if (ra == 0) {

      if (rv > 0) {
        rv = rv - rf;
        if (rv < 0) {
          rv = 0;
        }
      }
      if (rv < 0) {
        rv = rv + rf;
        if (rv > 0) {
          rv = 0;
        }
      }
    }

    t = t + tv;
    r = r + rv;

    convert();

    if (x + size / 2 >= 1000) {
      if (tv > 0) {
        tv = -Math.abs(tv);
      }
    }
    if (x - size / 2 <= 0) {
      if (tv < 0) {
        tv = Math.abs(tv);
      }
    }
  }
Ejemplo n.º 17
0
  public boolean onToolTouchEvent(MotionEvent event) {
    if (mapView == null || mapView.isClickable()) {
      return false;
    }

    Projection pj = mapView.getProjection();
    // handle drawing
    float currentX = event.getX();
    float currentY = event.getY();
    int deltaPixels = 100;

    int action = event.getAction();
    switch (action) {
      case MotionEvent.ACTION_DOWN:
      case MotionEvent.ACTION_MOVE:
        GeoPoint currentGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        GeoPoint plusPoint =
            pj.fromPixels(round(currentX + deltaPixels), round(currentY + deltaPixels));

        double touchLon = currentGeoPoint.getLongitude();
        double touchLat = currentGeoPoint.getLatitude();
        double lonPlus = plusPoint.getLongitude();
        double latPlus = plusPoint.getLatitude();
        double deltaX = Math.abs(touchLon - lonPlus);
        double deltaY = Math.abs(touchLat - latPlus);
        Coordinate touchCoord = new Coordinate(touchLon, touchLat);
        Envelope queryEnvelope = new Envelope(touchCoord);
        queryEnvelope.expandBy(deltaX, deltaY);

        List<GpsLogInfo> result = gpsLogInfoTree.query(queryEnvelope);
        if (result.size() == 0) {
          return true;
        } else {
          GpsLogInfo nearest = null;
          double minDist = Double.POSITIVE_INFINITY;
          for (GpsLogInfo info : result) {
            double dist = touchCoord.distance(info.pointXYZ);
            if (dist < minDist) {
              minDist = dist;
              nearest = info;
            }
          }
          gpsLogInfo = nearest;
        }
        break;
      case MotionEvent.ACTION_UP:
        gpsLogInfo = null;
        break;
    }
    EditManager.INSTANCE.invalidateEditingView();
    return true;
  }
Ejemplo n.º 18
0
 private boolean isValid(int[] queens, int row, int col) {
   for (int i = 0; i < row; ++i) {
     if (queens[i] == col) {
       return false;
     }
   }
   for (int i = 0; i < row; ++i) {
     if (Math.abs(col - queens[i]) == Math.abs(row - i)) {
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 19
0
  /**
   * Constructs a raster reference with given resolutions, origin and rotations. The origin maps to
   * the pixel location given by location.
   *
   * @param location of the origin on the upper left pixel.
   * @param resolutionX the resolution of one pixel on the x axis in the raster
   * @param resolutionY the resolution of one pixel on the y axis in the raster
   * @param rotationX rotation about x-axis
   * @param rotationY rotation about y-axis
   * @param origin0 ordinate of the origin of the first axis defined in the world crs
   * @param origin1 ordinate of the origin of the second axis defined in the world crs
   * @param crs in which the origin is defined.
   */
  public RasterGeoReference(
      OriginLocation location,
      double resolutionX,
      double resolutionY,
      double rotationX,
      double rotationY,
      double origin0,
      double origin1,
      ICRS crs) {

    this.crs = crs;
    if (crs != null) {
      transformer = new GeometryTransformer(crs);
      try {
        eastingAxis = crs.getEasting();
      } catch (ReferenceResolvingException e) {
        transformer = null;
        LOG.debug("CRS could not be resolved: {}", e.getLocalizedMessage());
      }
    } else {
      transformer = null;
    }
    // define a delta to which calculations will be correct. It is dependent on the highest
    // resolution. (smallest
    // value).
    delta = Math.min(Math.abs(resolutionX), Math.abs(resolutionY)) * 1E-6;

    this.resX = resolutionX;
    this.resY = resolutionY;
    this.rotX = rotationX;
    this.rotY = rotationY;

    transform =
        new AffineTransform(
            cos(rotationX) * resolutionX,
            sin(rotationY),
            -sin(rotationX),
            cos(rotationY) * resolutionY,
            origin0,
            origin1);
    try {
      invTransform = transform.createInverse();
    } catch (NoninvertibleTransformException e) {
      LOG.debug("No inverse transform available, this means the supplies values are not valid.", e);
      throw new IllegalArgumentException(
          "Could not create Raster Geo reference, the given values do not specify an affine transform: "
              + e.getLocalizedMessage());
    }
    this.location = location;
  }
Ejemplo n.º 20
0
  private int calcManhattan(int row, int col) {
    int value = blocks[row][col];

    int expectedCol = value % dimension() - 1;
    if (expectedCol < 0) expectedCol = dimension() - 1;

    int expectedRow = Math.max((value - expectedCol - 1) / dimension(), 0);

    int xOffset = Math.abs(expectedRow - row);
    int yOffset = Math.abs(expectedCol - col);

    int manhattan = xOffset + yOffset;

    return manhattan;
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(int data) throws Throwable {

    int result = 0;

    /* FIX: Add a check to prevent an overflow from occurring
     * NOTE: Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE so we must ensure the random value in
     *       data is not equal to Integer.MIN_VALUE */
    if ((Math.abs(data) != Integer.MIN_VALUE)
        && (Math.abs(data) <= (int) Math.sqrt(Integer.MAX_VALUE))) {
      result = (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("Input value is too large to perform squaring.");
    }
  }
Ejemplo n.º 22
0
 public double getMinDownRegulatedExpressionLevel() {
   Double minDownRegulatedExpressionLevel = null;
   for (DifferentialProfile differentialProfile : this) {
     double expressionLevel = differentialProfile.getMinDownRegulatedExpressionLevel();
     if (!Double.isNaN(expressionLevel)) {
       minDownRegulatedExpressionLevel =
           (minDownRegulatedExpressionLevel == null)
               ? Math.abs(expressionLevel)
               : min(minDownRegulatedExpressionLevel, Math.abs(expressionLevel));
     }
   }
   return minDownRegulatedExpressionLevel == null
       ? Double.NaN
       : negate(minDownRegulatedExpressionLevel);
 }
Ejemplo n.º 23
0
  public double get_h_value(Vertex t) {
    ArrayList<Vertex> chems = G.getChemV();
    double ans = 0;
    double t_dis = (this.d).get_t_dis_in_dList(d_list, t.getIndex());

    int v_c_index;
    int v_index;
    double v_dis;
    double dis;

    for (int i = 0; i < chems.size(); i++) {
      // get the index of the vertex in chem ver
      v_c_index = (chems.get(i)).getIndex();
      // get the index of him in d_list
      v_index = (this.d).getIndexInList(this.d_list, v_c_index);
      // get his distance
      v_dis = ((this.d_list).get(v_index)).get_dis();
      // compute the distance between t and chems.get(i):
      dis = Math.abs(t_dis - v_dis);
      // inc the ans
      ans = ans + dis;
    }

    return ans * 2;
  }
Ejemplo n.º 24
0
 /**
  * Given an Object value, pick a partition to store the data. Currently only String objects can be
  * hashed.
  *
  * @param value The value to hash.
  * @param partitionCount The number of partitions to choose from.
  * @return A value between 0 and partitionCount-1, hopefully pretty evenly distributed.
  */
 static int hashinate(Object value, int partitionCount) {
   if (value instanceof String) {
     String string = (String) value;
     try {
       byte bytes[] = string.getBytes("UTF-8");
       int hashCode = 0;
       int offset = 0;
       for (int ii = 0; ii < bytes.length; ii++) {
         hashCode = 31 * hashCode + bytes[offset++];
       }
       return java.lang.Math.abs(hashCode % partitionCount);
     } catch (UnsupportedEncodingException e) {
       hostLogger.l7dlog(
           Level.FATAL,
           LogKeys.host_TheHashinator_ExceptionHashingString.name(),
           new Object[] {string},
           e);
       HStore.crashDB();
     }
   }
   hostLogger.l7dlog(
       Level.FATAL,
       LogKeys.host_TheHashinator_AttemptedToHashinateNonLongOrString.name(),
       new Object[] {value.getClass().getName()},
       null);
   HStore.crashDB();
   return -1;
 }
Ejemplo n.º 25
0
  private static String millisToString(long millis, boolean text) {
    boolean negative = millis < 0;
    millis = java.lang.Math.abs(millis);

    millis /= 1000;
    int sec = (int) (millis % 60);
    millis /= 60;
    int min = (int) (millis % 60);
    millis /= 60;
    int hours = (int) millis;

    String time;
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    format.applyPattern("00");
    if (text) {
      if (millis > 0) time = (negative ? "-" : "") + hours + "h" + format.format(min) + "min";
      else if (min > 0) time = (negative ? "-" : "") + min + "min";
      else time = (negative ? "-" : "") + sec + "s";
    } else {
      if (millis > 0)
        time = (negative ? "-" : "") + hours + ":" + format.format(min) + ":" + format.format(sec);
      else time = (negative ? "-" : "") + min + ":" + format.format(sec);
    }
    return time;
  }
Ejemplo n.º 26
0
  /**
   * Returns the correlation coefficient of two double vectors.
   *
   * @param y1 double vector 1
   * @param y2 double vector 2
   * @param n the length of two double vectors
   * @return the correlation coefficient
   */
  public static final double correlation(double y1[], double y2[], int n) {

    int i;
    double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c;

    if (n <= 1) {
      return 1.0;
    }
    for (i = 0; i < n; i++) {
      av1 += y1[i];
      av2 += y2[i];
    }
    av1 /= (double) n;
    av2 /= (double) n;
    for (i = 0; i < n; i++) {
      y11 += (y1[i] - av1) * (y1[i] - av1);
      y22 += (y2[i] - av2) * (y2[i] - av2);
      y12 += (y1[i] - av1) * (y2[i] - av2);
    }
    if (y11 * y22 == 0.0) {
      c = 1.0;
    } else {
      c = y12 / Math.sqrt(Math.abs(y11 * y22));
    }

    return c;
  }
Ejemplo n.º 27
0
  // Cette methode va,pour un ascenseur donné, lui affecter une position de repositionnement la plus
  // appropiée
  public static void repositionnement(Ascenseur unAscenseur) throws InterruptedException {
    if (unAscenseur.getTabDestination().isEmpty()) {
      int ecart = 400, i, id = -1;
      ArrayList<Integer> tabRepositionement = new ArrayList<Integer>();
      if (Batterie.changement) {
        System.out.println("Changement : " + Batterie.cal.getDateActuelle().getTime());
        for (int k = 0; k < 6; k++) {
          // Initialise le tableau de reservation de position repos à faux. (Aucune position n'a été
          // réservée)
          Boolean bool = new Boolean(false);
          Batterie.tabResaPosition.set(k, bool);
        }
      }
      if (Batterie.semaine) {
        tabRepositionement = Batterie.tabPositionJournee;
      } else tabRepositionement = Batterie.tabPositionWeekEnd;
      Batterie.changement = false;

      System.out.println(unAscenseur.getIdAscenseur() + " : " + Batterie.tabResaPosition);
      for (i = 0; i < 6; i++) {
        // Si la position n'a pas été réservée
        if (!Batterie.tabResaPosition.get(i)) {
          int temp = Math.abs(unAscenseur.getPositionActuelle() - tabRepositionement.get(i));

          if (temp < ecart) {
            ecart = temp;
            id = i;
          }
        }
      }
      // Reservation de l'emplacement
      Batterie.tabResaPosition.set(id, true);
      unAscenseur.setPositionRepo(tabRepositionement.get(id));
    }
  } // Fin repositionnement
Ejemplo n.º 28
0
  public static float gaindequant(
      /* (o) quantized gain value */
      int index, /* (i) quantization index */
      float maxIn, /* (i) maximum of unquantized gain */
      int cblen) /* (i) number of quantization indices */ {
    float scale;

    /* obtain correct scale factor */

    scale = (float) (float) Math.abs(maxIn);

    if (scale < 0.1) {
      scale = (float) 0.1;
    }

    /* select the quantization table and return the decoded value */

    if (cblen == 8) {
      return scale * ilbc_constants.gain_sq3Tbl[index];
    } else if (cblen == 16) {
      return scale * ilbc_constants.gain_sq4Tbl[index];
    } else if (cblen == 32) {
      return scale * ilbc_constants.gain_sq5Tbl[index];
    }

    return 0.0f;
  }
Ejemplo n.º 29
0
  public static ArthurImage multiply(
      ArthurImage one, ArthurNumber two) { // change to ArthurNumber later
    double f = Math.abs(two.val);
    // get image
    BufferedImage image = JavaImageMath.clone(one.bf);

    // manipulate image
    WritableRaster raster = image.getRaster();
    int width = (int) (raster.getWidth() * f);
    int height = (int) (raster.getHeight() * f);

    BufferedImage collage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = collage.createGraphics();
    g2d.drawImage(image, 0, 0, width, height, null);
    g2d.dispose();

    // save image
    String outputFn =
        one.filename.substring(0, one.filename.indexOf(".jpg"))
            + "X"
            + // filename can't contain the / or *characters; decide later
            f
            + counter
            + ".jpg";
    counter++;

    return new ArthurImage(collage, outputFn);
  }
Ejemplo n.º 30
0
  @Override
  public double empiricalLoss(
      final org.drip.function.definition.RdToR1 funcLearnerRdToR1,
      final org.drip.spaces.instance.GeneralizedValidatedVector gvviX,
      final org.drip.spaces.instance.GeneralizedValidatedVector gvviY)
      throws java.lang.Exception {
    if (null == funcLearnerRdToR1
        || null == gvviX
        || !(gvviX instanceof org.drip.spaces.instance.ValidatedRd)
        || null == gvviY
        || !(gvviY instanceof org.drip.spaces.instance.ValidatedR1))
      throw new java.lang.Exception("LpLossLearner::empiricalLoss => Invalid Inputs");

    double[][] aadblX = ((org.drip.spaces.instance.ValidatedRd) gvviX).instance();

    double[] adblY = ((org.drip.spaces.instance.ValidatedR1) gvviY).instance();

    double dblEmpiricalLoss = 0.;
    int iNumSample = aadblX.length;

    if (iNumSample != adblY.length)
      throw new java.lang.Exception("LpLossLearner::empiricalLoss => Invalid Inputs");

    for (int i = 0; i < iNumSample; ++i)
      dblEmpiricalLoss +=
          java.lang.Math.pow(
              java.lang.Math.abs(funcLearnerRdToR1.evaluate(aadblX[i]) - adblY[i]),
              _dblLossExponent);

    return dblEmpiricalLoss / _dblLossExponent;
  }