コード例 #1
0
ファイル: BigFraction.java プロジェクト: PAMSE/APGBench
 /**
  * Gets the fraction as a <tt>double</tt>. This calculates the fraction as the numerator divided
  * by denominator.
  *
  * @return the fraction as a <tt>double</tt>
  * @see java.lang.Number#doubleValue()
  */
 @Override
 public double doubleValue() {
   double result = numerator.doubleValue() / denominator.doubleValue();
   if (Double.isNaN(result)) {
     // Numerator and/or denominator must be out of range:
     // Calculate how far to shift them to put them in range.
     int shift = Math.max(numerator.bitLength(), denominator.bitLength()) - Double.MAX_EXPONENT;
     result =
         numerator.shiftRight(shift).doubleValue() / denominator.shiftRight(shift).doubleValue();
   }
   return result;
 }
コード例 #2
0
  @Override
  public double getDoubleValue() {
    double result = wholePartValue.doubleValue();

    if (radix == 16) {
      result += fractionPartValue.doubleValue() * Math.pow(2, -4 * fractionLength);
      result *= Math.pow(2, exponentValue.doubleValue());
    } else if (radix == 10) {
      result += fractionPartValue.doubleValue() * Math.pow(10, -fractionLength);
      result *= Math.pow(10, exponentValue.doubleValue());
    } else {
      throw new RuntimeException("Only know base 10 and 16");
    }
    return result;
  }
コード例 #3
0
ファイル: MathArithTypeEnum.java プロジェクト: arberzal/esper
 public Number compute(Number d1, Number d2) {
   BigInteger b1 = (BigInteger) d1;
   BigInteger b2 = (BigInteger) d2;
   if (b2.doubleValue() == 0) {
     return null;
   }
   return b1.divide(b2);
 }
コード例 #4
0
ファイル: MathArithTypeEnum.java プロジェクト: arberzal/esper
 public Number compute(Number d1, Number d2) {
   BigInteger s1 = convOne.coerceBoxedBigInt(d1);
   BigInteger s2 = convTwo.coerceBoxedBigInt(d2);
   if (s2.doubleValue() == 0) {
     return null;
   }
   return s1.divide(s2);
 }
コード例 #5
0
ファイル: Bet.java プロジェクト: prodigeni/chancecoinj
  public static Transaction create(String source, BigInteger bet, Double chance, Double payout)
      throws Exception {
    BigInteger chaSupply = Util.chaSupplyForBetting();
    if (source.equals("")) throw new Exception("Please specify a source address.");
    if (!(bet.compareTo(BigInteger.ZERO) > 0)) throw new Exception("Please bet more than zero.");
    if (!(chance > 0.0 && chance < 100.0))
      throw new Exception("Please specify a chance between 0 and 100.");
    if (!(payout > 1.0)) throw new Exception("Please specify a payout greater than 1.");
    if (!(Util.roundOff(chance, 6)
        == Util.roundOff(100.0 / (payout / (1.0 - Config.houseEdge)), 6)))
      throw new Exception("Please specify a chance and payout that are congruent.");
    if (!(bet.compareTo(Util.getBalance(source, "CHA")) <= 0))
      throw new Exception("Please specify a bet that is smaller than your CHA balance.");
    if (!((payout - 1.0) * bet.doubleValue() < chaSupply.doubleValue() * Config.maxProfit))
      throw new Exception(
          "Please specify a bet with a payout less than the maximum percentage of the house bankroll you can win.");

    Blocks blocks = Blocks.getInstance();
    ByteBuffer byteBuffer = ByteBuffer.allocate(length + 4);
    byteBuffer.putInt(0, id);
    byteBuffer.putLong(0 + 4, bet.longValue());
    byteBuffer.putDouble(8 + 4, chance);
    byteBuffer.putDouble(16 + 4, payout);
    List<Byte> dataArrayList = Util.toByteArrayList(byteBuffer.array());
    dataArrayList.addAll(0, Util.toByteArrayList(Config.prefix.getBytes()));
    byte[] data = Util.toByteArray(dataArrayList);

    String dataString = "";
    try {
      dataString = new String(data, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
    }

    Transaction tx =
        blocks.transaction(
            source, "", BigInteger.ZERO, BigInteger.valueOf(Config.minFee), dataString);
    return tx;
  }
コード例 #6
0
 /**
  * Increments value in each column. If the value is bounded type (e.g. short) it will cycle the
  * values.
  */
 private void generateRow() {
   List<Object> newRow = new ArrayList<Object>(types.size());
   String incrementedString = incrementString(staticStringValue, rowNumber);
   for (Class<?> type : types) {
     if (type.equals(Integer.class)) {
       newRow.add(rowNumber.intValue());
     } else if (type.equals(java.lang.Short.class)) {
       newRow.add(rowNumber.shortValue());
     } else if (type.equals(java.lang.Long.class)) {
       newRow.add(rowNumber.longValue());
     } else if (type.equals(java.lang.Float.class)) {
       newRow.add(rowNumber.floatValue() / 10);
     } else if (type.equals(java.lang.Double.class)) {
       newRow.add(rowNumber.doubleValue() / 10);
     } else if (type.equals(java.lang.Character.class)) {
       newRow.add((char) ((((rowNumber.byteValue() & 0xff) + 2) % 26) + 97));
     } else if (type.equals(java.lang.Byte.class)) {
       newRow.add(rowNumber.byteValue());
     } else if (type.equals(java.lang.Boolean.class)) {
       newRow.add(rowNumber.intValue() % 2 != 0);
     } else if (type.equals(java.math.BigInteger.class)) {
       newRow.add(rowNumber);
     } else if (type.equals(java.math.BigDecimal.class)) {
       newRow.add(new BigDecimal(rowNumber, 1));
     } else if (type.equals(java.sql.Date.class)) {
       newRow.add(new Date(DAY_SECONDS * 1000 * (rowNumber.intValue() % DATE_PERIOD)));
     } else if (type.equals(java.sql.Time.class)) {
       newRow.add(new Time((rowNumber.intValue() % DAY_SECONDS) * 1000));
     } else if (type.equals(java.sql.Timestamp.class)) {
       newRow.add(new Timestamp(rowNumber.longValue()));
     } else if (type.equals(TypeFacility.RUNTIME_TYPES.CLOB)) {
       newRow.add(
           this.config.getTypeFacility().convertToRuntimeType(incrementedString.toCharArray()));
     } else if (type.equals(TypeFacility.RUNTIME_TYPES.BLOB)
         || type.equals(TypeFacility.RUNTIME_TYPES.VARBINARY)) {
       newRow.add(
           this.config.getTypeFacility().convertToRuntimeType(incrementedString.getBytes()));
     } else {
       newRow.add(incrementedString);
     }
   }
   row = newRow;
 }
コード例 #7
0
  protected void convertNumberToDouble() throws IOException, JsonParseException {
    /* 05-Aug-2008, tatus: Important note: this MUST start with
     *   more accurate representations, since we don't know which
     *   value is the original one (others get generated when
     *   requested)
     */

    if ((_numTypesValid & NR_BIGDECIMAL) != 0) {
      _numberDouble = _numberBigDecimal.doubleValue();
    } else if ((_numTypesValid & NR_BIGINT) != 0) {
      _numberDouble = _numberBigInt.doubleValue();
    } else if ((_numTypesValid & NR_LONG) != 0) {
      _numberDouble = (double) _numberLong;
    } else if ((_numTypesValid & NR_INT) != 0) {
      _numberDouble = (double) _numberInt;
    } else {
      _throwInternal(); // should never get here
    }

    _numTypesValid |= NR_DOUBLE;
  }
コード例 #8
0
ファイル: DataType.java プロジェクト: inexas/oak
  /**
   * Type converts values to other classes. For example an Integer can be converted to a Long.
   *
   * @param <T> Data Type.
   * @param value The value to be converted.
   * @param to The class to be converted to. Must be one of the Java types corresponding to the
   *     DataTypes.
   * @return The converted value.
   * @throws TypeMismatchException Thrown desired class is incompatible with the source class.
   * @throws OverflowException Thrown only on narrowing value conversions, e.g from a BigInteger to
   *     an Integer.
   */
  @Nullable
  public static <T> T convert(Object value, Class<?> to)
      throws TypeMismatchException, OverflowException {
    final Object result;

    if (value == null || value.getClass() == to) {
      result = value;
    } else {
      final Class<?> from = value.getClass();
      try {
        if (from == Integer.class) { // Integer -> ...
          if (to == Long.class) {
            result = new Long(((Number) value).longValue());
          } else if (to == BigInteger.class) {
            result = BigInteger.valueOf(((Number) value).intValue());
          } else if (to == Float.class) {
            result = new Float(((Number) value).floatValue());
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            // Use intValue() to avoid precision errors
            result = new BigDecimal(((Number) value).intValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Long.class) { // Long -> ...
          if (to == Integer.class) {
            final long l = ((Long) value).longValue();
            if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) l);
          } else if (to == BigInteger.class) {
            result = BigInteger.valueOf(((Number) value).longValue());
          } else if (to == Float.class) {
            result = new Float(((Number) value).floatValue());
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            // Use longValue() to avoid precision errors
            result = new BigDecimal(((Number) value).longValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == BigInteger.class) { // BigInteger -> ...
          final BigInteger bi = (BigInteger) value;
          if (to == Integer.class) {
            result = new Integer(bi.intValueExact());
          } else if (to == Long.class) {
            result = new Long(bi.longValueExact());
          } else if (to == Float.class) {
            final float f1 = bi.floatValue();
            if (f1 == Float.NEGATIVE_INFINITY || f1 == Float.POSITIVE_INFINITY) {
              throw new OverflowException(bi, to);
            }
            result = new Float(f1);
          } else if (to == Double.class) {
            final double d = bi.doubleValue();
            if (d == Double.NEGATIVE_INFINITY || d == Double.POSITIVE_INFINITY) {
              throw new OverflowException(bi, to);
            }
            result = new Double(d);
          } else if (to == BigDecimal.class) {
            result = new BigDecimal(bi);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Float.class) { // Float -> ...
          final float fl = ((Float) value).floatValue();
          if (to == Integer.class) {
            if (fl < Integer.MIN_VALUE || fl > Integer.MAX_VALUE | fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) fl);
          } else if (to == Long.class) {
            if (fl < Long.MIN_VALUE || fl > Long.MAX_VALUE | fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Long((long) fl);
          } else if (to == BigInteger.class) {
            if (fl % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            final BigDecimal bd = BigDecimal.valueOf(fl);
            result = bd.toBigInteger();
          } else if (to == Double.class) {
            result = new Double(((Number) value).doubleValue());
          } else if (to == BigDecimal.class) {
            result = BigDecimal.valueOf(fl);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == Double.class) { // Double -> ...
          final double d = ((Double) value).doubleValue();
          if (to == Integer.class) {
            if (d < Integer.MIN_VALUE || d > Integer.MAX_VALUE || d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Integer((int) d);
          } else if (to == Long.class) { // OK
            if (d < Long.MIN_VALUE || d > Long.MAX_VALUE || d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            result = new Long((int) d);
          } else if (to == BigInteger.class) { // OK
            if (d % 1 > 0) {
              throw new OverflowException((Number) value, to);
            }
            final BigDecimal bd = BigDecimal.valueOf(d);
            result = bd.toBigInteger();
          } else if (to == Float.class) { // OK
            if (d < -Float.MAX_VALUE || d > Float.MAX_VALUE) {
              throw new OverflowException((Number) value, to);
            }
            result = new Float((float) d);
          } else if (to == BigDecimal.class) { // OK
            result = BigDecimal.valueOf(d);
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else if (from == BigDecimal.class) { // BigDecimal -> ...
          final BigDecimal bd = (BigDecimal) value;
          if (to == Integer.class) { // OK
            result = new Integer(bd.intValueExact());
          } else if (to == Long.class) { // OK
            result = new Long(bd.longValueExact());
          } else if (to == BigInteger.class) { // OK
            // BigDecimal modulus
            final BigDecimal remainder = bd.remainder(BigDecimal.ONE);
            if (!remainder.equals(BigDecimal.ZERO)) {
              throw new OverflowException(bd, to);
            }
            result = bd.toBigInteger();
          } else if (to == Float.class) { // OK
            if (bd.compareTo(BigDecimal_MIN_FLOAT) < 0 || bd.compareTo(BigDecimal_MAX_FLOAT) > 0) {
              throw new OverflowException(bd, to);
            }
            result = new Float(bd.floatValue());
          } else if (to == Double.class) { // OK
            if (bd.compareTo(BigDecimal_MIN_DOUBLE) < 0
                || bd.compareTo(BigDecimal_MAX_DOUBLE) > 0) {
              throw new OverflowException(bd, to);
            }
            result = new Double(bd.doubleValue());
          } else {
            throw new TypeMismatchException(value.getClass(), to);
          }

        } else {
          throw new UnexpectedException("convert: " + from.getName());
        }
      } catch (final ArithmeticException e) {
        // Thrown by intValueExact() etc.
        throw new OverflowException((Number) value, to);
      }
    }

    @SuppressWarnings("unchecked")
    final T t = (T) result;
    return t;
  }
コード例 #9
0
 // TODO
 public static double satoshiToBTC(BigInteger satoshis) {
   return satoshis.doubleValue() / BTC.doubleValue();
 }
コード例 #10
0
 /**
  * Returns a <code>double</code> whose value is <tt>(this<sup>exponent</sup>)</tt>, returning the
  * result in reduced form.
  *
  * @param exponent exponent to which this <code>BigFraction</code> is to be raised.
  * @return <tt>this<sup>exponent</sup></tt>.
  */
 public double pow(final double exponent) {
   return Math.pow(numerator.doubleValue(), exponent)
       / Math.pow(denominator.doubleValue(), exponent);
 }
コード例 #11
0
 /**
  * Gets the fraction as a <tt>double</tt>. This calculates the fraction as the numerator divided
  * by denominator.
  *
  * @return the fraction as a <tt>double</tt>
  * @see java.lang.Number#doubleValue()
  */
 @Override
 public double doubleValue() {
   return numerator.doubleValue() / denominator.doubleValue();
 }
コード例 #12
0
  private void refreshVirtualNodes(Host host, LinkedList<ChordRoutingTable> deleted) {
    if (host != null) {
      for (AbstractChordRoutingTable rt :
          ((ChordNode) host.getOverlay(AbstractChordNode.class)).getVirtualNodes()) {
        // check if this virtual node does not exist:
        if (!virtualNodes.containsKey(((ChordRoutingTable) rt).getChordId())) {
          // create node!

          // TODO: this is quite sick hacked together!

          NetID n =
              new NetID() {
                @Override
                public long getTransmissionSize() {
                  return 0;
                }
              };

          // create attributes
          Map<String, Serializable> attributes = new LinkedHashMap<String, Serializable>();
          attributes.put("ChordID", ((ChordRoutingTable) rt).getChordId());

          // compute position on ring:
          double div = 0.0;
          BigInteger MAX_KEY_SIZE =
              new BigInteger("1461501637330902918203684832716283019655932542975");

          div =
              ((ChordRoutingTable) rt).getChordId().getValue().doubleValue()
                  / MAX_KEY_SIZE.doubleValue();

          float x = 0.5f + 0.4f * (float) Math.sin(2 * Math.PI * div);
          float y = 0.5f + 0.4f * (float) Math.cos(2 * Math.PI * div);

          // add virtual node to visualisation
          getTranslator()
              .overlayNodeAdded(n, "vNode", new PositionInfo(new Coords(x, y)), attributes);
          virtualNodes.put(((ChordRoutingTable) rt).getChordId(), n);

          // add edge from real node to virtual node:
          EdgeHandle h =
              this.addEdge(
                  rt.getMasterNode().getHost().getNetLayer().getNetID(),
                  n,
                  Color.BLUE,
                  "virtualNodeEdge");

          virtualNodeEdges.put(((ChordRoutingTable) rt).getChordId(), h);
        }
      }

      // remove thoses who have been deleted:
      if (deleted != null) {
        for (AbstractChordRoutingTable rt : deleted) {
          if (virtualNodeEdges.containsKey(((ChordRoutingTable) rt).getChordId())) {
            virtualNodeEdges.get(((ChordRoutingTable) rt).getChordId()).remove();
          }

          if (virtualNodes.containsKey(((ChordRoutingTable) rt).getChordId())) {
            getTranslator()
                .overlayNodeRemoved(virtualNodes.get(((ChordRoutingTable) rt).getChordId()));
          }
        }
      }
    }
  }
コード例 #13
0
ファイル: UnsignedLong.java プロジェクト: sarahCla/Schnauzer
 @Override
 public double doubleValue() {
   return value.doubleValue();
 }
コード例 #14
0
ファイル: Bet.java プロジェクト: prodigeni/chancecoinj
  public static void parse(Integer txIndex, List<Byte> message) {
    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery("select * from transactions where tx_index=" + txIndex.toString());
    try {
      if (rs.next()) {
        String source = rs.getString("source");
        String destination = rs.getString("destination");
        BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
        BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
        Integer blockIndex = rs.getInt("block_index");
        String txHash = rs.getString("tx_hash");

        ResultSet rsCheck =
            db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'");
        if (rsCheck.next()) return;

        if (message.size() == length) {
          ByteBuffer byteBuffer = ByteBuffer.allocate(length);
          for (byte b : message) {
            byteBuffer.put(b);
          }
          BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0));
          Double chance = byteBuffer.getDouble(8);
          Double payout = byteBuffer.getDouble(16);
          Double houseEdge = Config.houseEdge;
          // PROTOCOL CHANGE
          Double oldHouseEdge = 0.02;
          Boolean payoutChanceCongruent =
              Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6)
                  || Util.roundOff(chance, 6)
                      == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6);
          BigInteger chaSupply = Util.chaSupplyForBetting();
          String validity = "invalid";
          if (!source.equals("")
              && bet.compareTo(BigInteger.ZERO) > 0
              && chance > 0.0
              && chance < 100.0
              && payout > 1.0
              && payoutChanceCongruent) {
            if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) {
              if ((payout - 1.0) * bet.doubleValue() < chaSupply.doubleValue() * Config.maxProfit) {
                validity = "valid";
                Util.debit(source, "CHA", bet, "Debit bet amount", txHash, blockIndex);
              }
            }
          }
          db.executeUpdate(
              "insert into bets(tx_index, tx_hash, block_index, source, bet, chance, payout, profit, cha_supply, validity) values('"
                  + txIndex.toString()
                  + "','"
                  + txHash
                  + "','"
                  + blockIndex.toString()
                  + "','"
                  + source
                  + "','"
                  + bet.toString()
                  + "','"
                  + chance.toString()
                  + "','"
                  + payout.toString()
                  + "','0','"
                  + chaSupply.toString()
                  + "','"
                  + validity
                  + "')");
        }
      }
    } catch (SQLException e) {
    }
  }
コード例 #15
0
ファイル: IntegerExtensions.java プロジェクト: rnsmit/gravel
 public static double doubleDivFromLargeInteger_(int receiver, BigInteger argument) {
   return (argument.doubleValue() / receiver);
 }
コード例 #16
0
ファイル: Atan2Builtin.java プロジェクト: smarr/graal-erl
 @Specialization
 public double atan2(double a, BigInteger b) {
   return Math.atan2(a, b.doubleValue());
 }
コード例 #17
0
ファイル: MNatural.java プロジェクト: TU-Berlin/Mumie
 public double getDouble() {
   if (isPosInfinity()) return Double.POSITIVE_INFINITY;
   if (isNegInfinity()) return Double.NEGATIVE_INFINITY;
   return m_value.doubleValue();
 }
コード例 #18
0
ファイル: IntegerExtensions.java プロジェクト: rnsmit/gravel
 public static float floatDivFromLargeInteger_(int receiver, BigInteger argument) {
   return (float) (argument.doubleValue() / receiver);
 }
コード例 #19
0
ファイル: Atan2Builtin.java プロジェクト: smarr/graal-erl
 @Specialization
 public double atan2(BigInteger a, double b) {
   return Math.atan2(a.doubleValue(), b);
 }
コード例 #20
0
ファイル: PrimFn.java プロジェクト: aaronc/idris-java-rts
 public static double LIntFloat(BigInteger x) {
   return x.doubleValue();
 }
コード例 #21
0
ファイル: Bet.java プロジェクト: prodigeni/chancecoinj
  public static void resolve() {
    // resolve bets

    logger.info("Resolving bets");

    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery(
            "select block_time,blocks.block_index as block_index,tx_index,tx_hash,source,bet,payout,chance,cha_supply from bets,blocks where bets.block_index=blocks.block_index and bets.validity='valid' and bets.resolved IS NOT 'true';");
    // if (true) return;

    SimpleDateFormat dateFormatStandard = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    SimpleDateFormat dateFormatDateTimeLotto = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    SimpleDateFormat dateFormatDateLotto = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat dateFormatHour = new SimpleDateFormat("HH");
    SimpleDateFormat dateFormatMinute = new SimpleDateFormat("mm");
    TimeZone newYork = TimeZone.getTimeZone("America/New_York");
    TimeZone UTC = TimeZone.getTimeZone("UTC");
    dateFormatStandard.setTimeZone(UTC);
    dateFormatDateLotto.setTimeZone(newYork);
    dateFormatDateTimeLotto.setTimeZone(newYork);
    dateFormatHour.setTimeZone(newYork);
    dateFormatMinute.setTimeZone(newYork);

    try {
      while (rs.next()) {
        String source = rs.getString("source");
        String txHash = rs.getString("tx_hash");
        Integer txIndex = rs.getInt("tx_index");
        Integer blockIndex = rs.getInt("block_index");
        BigInteger bet = BigInteger.valueOf(rs.getLong("bet"));
        Double payout = rs.getDouble("payout");
        Double chance = rs.getDouble("chance");
        BigInteger chaSupply = BigInteger.valueOf(rs.getLong("cha_supply"));
        Date blockTime = new Date((long) rs.getLong("block_time") * 1000);

        logger.info("Attempting to resolve bet " + txHash);

        String lottoDate = dateFormatDateLotto.format(blockTime);
        Integer hour = Integer.parseInt(dateFormatHour.format(blockTime));
        Integer minute = Integer.parseInt(dateFormatMinute.format(blockTime));
        if (hour >= 23 && minute >= 56) {
          lottoDate = dateFormatDateLotto.format(addDays(blockTime, 1));
        }
        String lottoUrl =
            "http://nylottery.ny.gov/wps/PA_NYSLNumberCruncher/NumbersServlet?game=quick&action=winningnumbers&startSearchDate="
                + lottoDate
                + "&endSearchDate=&pageNo=&last=&perPage=999&sort=";
        String lottoPage = Util.getPage(lottoUrl);
        logger.info("Getting lottery numbers " + lottoUrl);
        try {
          ObjectMapper objectMapper = new ObjectMapper();
          objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
          LottoResult lottoMap = objectMapper.readValue(lottoPage, LottoResult.class);

          for (LottoDraw draw : lottoMap.draw) {
            Date time = dateFormatDateTimeLotto.parse(draw.date);
            if (time.after(blockTime)) {
              logger.info("Found lottery numbers we can use to resolve bet");
              BigInteger denominator =
                  combinations(BigInteger.valueOf(80), BigInteger.valueOf(20))
                      .subtract(BigInteger.ONE);
              BigInteger n = BigInteger.ZERO;
              BigInteger i = BigInteger.ONE;
              for (BigInteger number : draw.numbersDrawn) {
                n = n.add(combinations(number.subtract(BigInteger.ONE), i));
                i = i.add(BigInteger.ONE);
              }
              Double rollA = n.doubleValue() / (denominator.doubleValue());
              Double rollB =
                  (new BigInteger(txHash.substring(10, txHash.length()), 16))
                          .mod(BigInteger.valueOf(1000000000))
                          .doubleValue()
                      / 1000000000.0;
              Double roll = (rollA + rollB) % 1.0;
              roll = roll * 100.0;

              logger.info("Roll = " + roll.toString() + ", chance = " + chance.toString());

              BigInteger profit = BigInteger.ZERO;
              if (roll < chance) {
                logger.info("The bet is a winner");
                // win
                profit =
                    new BigDecimal(
                            bet.doubleValue()
                                * (payout.doubleValue() - 1.0)
                                * chaSupply.doubleValue()
                                / (chaSupply.doubleValue()
                                    - bet.doubleValue() * payout.doubleValue()))
                        .toBigInteger();
                BigInteger credit = profit.add(bet);
                Util.credit(source, "CHA", credit, "Bet won", txHash, blockIndex);
              } else {
                logger.info("The bet is a loser");
                // lose
                profit = bet.multiply(BigInteger.valueOf(-1));
              }
              db.executeUpdate(
                  "update bets set profit='"
                      + profit.toString()
                      + "', rolla='"
                      + (rollA * 100.0)
                      + "', rollb='"
                      + (rollB * 100.0)
                      + "', roll='"
                      + roll
                      + "', resolved='true' where tx_index='"
                      + txIndex
                      + "';");
              break;
            }
          }
        } catch (Exception e) {
          logger.error(e.toString());
        }
      }
    } catch (SQLException e) {
      logger.error(e.toString());
    }
  }
コード例 #22
0
 /**
  * @param value the value to divide
  * @param divisor the # to divide value by
  * @return String null if value or divisor is null other the resulting double value as a string
  */
 private String divide(BigInteger value, BigInteger divisor) {
   if (divisor == null || value == null) return null;
   if (divisor.longValue() == 0) return new String("0");
   return Double.toString(value.doubleValue() / divisor.longValue());
 }
コード例 #23
0
ファイル: Bet.java プロジェクト: prodigeni/chancecoinj
  public static List<BetInfo> getPending(String source) {
    Database db = Database.getInstance();
    ResultSet rs =
        db.executeQuery(
            "select * from transactions where block_index<0 and source='"
                + source
                + "' order by tx_index desc;");
    List<BetInfo> bets = new ArrayList<BetInfo>();
    Blocks blocks = Blocks.getInstance();
    try {
      while (rs.next()) {
        String destination = rs.getString("destination");
        BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
        BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
        Integer blockIndex = rs.getInt("block_index");
        String txHash = rs.getString("tx_hash");
        Integer txIndex = rs.getInt("tx_index");
        String dataString = rs.getString("data");

        ResultSet rsCheck =
            db.executeQuery("select * from bets where tx_index='" + txIndex.toString() + "'");
        if (!rsCheck.next()) {
          List<Byte> messageType = blocks.getMessageTypeFromTransaction(dataString);
          List<Byte> message = blocks.getMessageFromTransaction(dataString);
          if (messageType.get(3) == Bet.id.byteValue() && message.size() == length) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(length);
            for (byte b : message) {
              byteBuffer.put(b);
            }
            BigInteger bet = BigInteger.valueOf(byteBuffer.getLong(0));
            Double chance = byteBuffer.getDouble(8);
            Double payout = byteBuffer.getDouble(16);
            Double houseEdge = Config.houseEdge;
            // PROTOCOL CHANGE
            Double oldHouseEdge = 0.02;
            Boolean payoutChanceCongruent =
                Util.roundOff(chance, 6) == Util.roundOff(100.0 / (payout / (1.0 - houseEdge)), 6)
                    || Util.roundOff(chance, 6)
                        == Util.roundOff(100.0 / (payout / (1.0 - oldHouseEdge)), 6);
            BigInteger chaSupply = Util.chaSupplyForBetting();
            String validity = "invalid";
            if (!source.equals("")
                && bet.compareTo(BigInteger.ZERO) > 0
                && chance > 0.0
                && chance < 100.0
                && payout > 1.0
                && payoutChanceCongruent) {
              if (bet.compareTo(Util.getBalance(source, "CHA")) <= 0) {
                if ((payout - 1.0) * bet.doubleValue()
                    < chaSupply.doubleValue() * Config.maxProfit) {
                  BetInfo betInfo = new BetInfo();
                  betInfo.bet = bet;
                  betInfo.chance = chance;
                  betInfo.payout = payout;
                  betInfo.source = source;
                  betInfo.txHash = txHash;
                  bets.add(betInfo);
                }
              }
            }
          }
        }
      }
    } catch (SQLException e) {
    }
    return bets;
  }
コード例 #24
0
ファイル: BigDecimalMath.java プロジェクト: rizar/matrix
  public static BigDecimal sqrt(BigDecimal squarD, int scalar) {
    // Static constants - perhaps initialize in class Vladimir!
    BigDecimal TWO = new BigDecimal(2);
    double SQRT_10 = 3.162277660168379332;
    MathContext rootMC = new MathContext(scalar);

    // General number and precision checking
    int sign = squarD.signum();
    if (sign == -1) throw new ArithmeticException("\nSquare root of a negative number: " + squarD);
    else if (sign == 0) return squarD.round(rootMC);

    int prec = rootMC.getPrecision(); // the requested precision
    if (prec == 0)
      throw new IllegalArgumentException("\nMost roots won't have infinite precision = 0");

    // Initial precision is that of double numbers 2^63/2 ~ 4E18
    int BITS = 62; // 63-1 an even number of number bits
    int nInit = 16; // precision seems 16 to 18 digits
    MathContext nMC = new MathContext(18, RoundingMode.HALF_UP);

    // Iteration variables, for the square root x and the reciprocal v
    BigDecimal x = null, e = null; // initial x: x0 ~ sqrt()
    BigDecimal v = null, g = null; // initial v: v0 = 1/(2*x)

    // Estimate the square root with the foremost 62 bits of squarD
    BigInteger bi = squarD.unscaledValue(); // bi and scale are a tandem
    int biLen = bi.bitLength();
    int shift = Math.max(0, biLen - BITS + (biLen % 2 == 0 ? 0 : 1)); // even
    // shift..
    bi = bi.shiftRight(shift); // ..floors to 62 or 63 bit BigInteger

    double root = Math.sqrt(bi.doubleValue());
    BigDecimal halfBack = new BigDecimal(BigInteger.ONE.shiftLeft(shift / 2));

    int scale = squarD.scale();
    if (scale % 2 == 1) // add half scales of the root to odds..
    root *= SQRT_10; // 5 -> 2, -5 -> -3 need half a scale more..
    scale = (int) Math.floor(scale / 2.); // ..where 100 -> 10 shifts the
    // scale

    // Initial x - use double root - multiply by halfBack to unshift - set
    // new scale
    x = new BigDecimal(root, nMC);
    x = x.multiply(halfBack, nMC); // x0 ~ sqrt()
    if (scale != 0) x = x.movePointLeft(scale);

    if (prec < nInit) // for prec 15 root x0 must surely be OK
    return x.round(rootMC); // return small prec roots without
    // iterations

    // Initial v - the reciprocal
    v = BigDecimal.ONE.divide(TWO.multiply(x), nMC); // v0 = 1/(2*x)

    // Collect iteration precisions beforehand
    ArrayList<Integer> nPrecs = new ArrayList<Integer>();

    assert nInit > 3 : "Never ending loop!"; // assume nInit = 16 <= prec

    // Let m be the exact digits precision in an earlier! loop
    for (int m = prec + 1; m > nInit; m = m / 2 + (m > 100 ? 1 : 2)) nPrecs.add(m);

    // The loop of "Square Root by Coupled Newton Iteration" for simpletons
    for (int i = nPrecs.size() - 1; i > -1; i--) {
      // Increase precision - next iteration supplies n exact digits
      nMC =
          new MathContext(
              nPrecs.get(i), (i % 2 == 1) ? RoundingMode.HALF_UP : RoundingMode.HALF_DOWN);

      // Next x // e = d - x^2
      e = squarD.subtract(x.multiply(x, nMC), nMC);
      if (i != 0) x = x.add(e.multiply(v, nMC)); // x += e*v ~ sqrt()
      else {
        x = x.add(e.multiply(v, rootMC), rootMC); // root x is ready!
        break;
      }

      // Next v // g = 1 - 2*x*v
      g = BigDecimal.ONE.subtract(TWO.multiply(x).multiply(v, nMC));

      v = v.add(g.multiply(v, nMC)); // v += g*v ~ 1/2/sqrt()
    }

    return x; // return sqrt(squarD) with precision of rootMC
  }