List of usage examples for java.math BigInteger ONE
BigInteger ONE
To view the source code for java.math BigInteger ONE.
Click Source Link
From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.WorkerTest.java
private void runAndTestWorker(int numShards, int threadPoolSize) throws Exception { final int numberOfRecordsPerShard = 10; final String kinesisShardPrefix = "kinesis-0-"; final BigInteger startSeqNum = BigInteger.ONE; List<Shard> shardList = KinesisLocalFileDataCreator.createShardList(numShards, kinesisShardPrefix, startSeqNum);/*from w w w. j a v a 2 s. c o m*/ Assert.assertEquals(numShards, shardList.size()); List<KinesisClientLease> initialLeases = new ArrayList<KinesisClientLease>(); for (Shard shard : shardList) { KinesisClientLease lease = ShardSyncer.newKCLLease(shard); lease.setCheckpoint(ExtendedSequenceNumber.AT_TIMESTAMP); initialLeases.add(lease); } runAndTestWorker(shardList, threadPoolSize, initialLeases, callProcessRecordsForEmptyRecordList, numberOfRecordsPerShard); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The inverse trigonometric sine./*from w ww.ja v a 2 s . com*/ * * @param x the argument. * @return the arcsin(x) in radians. */ static public BigDecimal asin(final BigDecimal x) { if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) { throw new ArithmeticException("Out of range argument " + x.toString() + " of asin"); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else if (x.compareTo(BigDecimal.ONE) == 0) { /* arcsin(1) = pi/2 */ double errpi = Math.sqrt(x.ulp().doubleValue()); MathContext mc = new MathContext(err2prec(3.14159, errpi)); return pi(mc).divide(new BigDecimal(2)); } else if (x.compareTo(BigDecimal.ZERO) < 0) { return asin(x.negate()).negate(); } else if (x.doubleValue() > 0.7) { final BigDecimal xCompl = BigDecimal.ONE.subtract(x); final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(xCompl, 3); final BigDecimal xhighprV = divideRound(xhighpr, 4); BigDecimal resul = BigDecimal.ONE; /* x^(2i+1) */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + i)); if (i == 1) { xpowi = xhighprV; } else { xpowi = multiplyRound(xpowi, xhighprV); } BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); /* series started 1+x/12+... which yields an estimate of the sums error */ if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) { break; } } /* sqrt(2*z)*(1+...) */ xpowi = sqrt(xhighpr.multiply(new BigDecimal(2))); resul = multiplyRound(xpowi, resul); MathContext mc = new MathContext(resul.precision()); BigDecimal pihalf = pi(mc).divide(new BigDecimal(2)); mc = new MathContext(err2prec(resul.doubleValue(), eps)); return pihalf.subtract(resul, mc); } else { /* absolute error in the result is err(x)/sqrt(1-x^2) to lowest order */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(x, 2); final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); BigDecimal resul = xhighpr.plus(); /* x^(2i+1) */ BigDecimal xpowi = xhighpr; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + (2 * i))); xpowi = multiplyRound(xpowi, xhighprSq); BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); if (Math.abs(c.doubleValue()) < 0.1 * eps) { break; } } MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } }
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. */// w ww . j a v a2s .com public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java
Object GetSmallerValue(Object v) { byte type = DataType.findType(v); if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP) return null; switch (type) { case DataType.CHARARRAY: String str = (String) v; if (str.length() > 0) return str.substring(0, str.length() - 1); else//from w w w.j ava 2 s .c o m return null; case DataType.BYTEARRAY: DataByteArray data = (DataByteArray) v; if (data.size() > 0) return new DataByteArray(data.get(), 0, data.size() - 1); else return null; case DataType.INTEGER: return Integer.valueOf((Integer) v - 1); case DataType.LONG: return Long.valueOf((Long) v - 1); case DataType.FLOAT: return Float.valueOf((Float) v - 1); case DataType.DOUBLE: return Double.valueOf((Double) v - 1); case DataType.BIGINTEGER: return ((BigInteger) v).subtract(BigInteger.ONE); case DataType.BIGDECIMAL: return ((BigDecimal) v).subtract(BigDecimal.ONE); case DataType.DATETIME: DateTime dt = (DateTime) v; if (dt.getMillisOfSecond() != 0) { return dt.minusMillis(1); } else if (dt.getSecondOfMinute() != 0) { return dt.minusSeconds(1); } else if (dt.getMinuteOfHour() != 0) { return dt.minusMinutes(1); } else if (dt.getHourOfDay() != 0) { return dt.minusHours(1); } else { return dt.minusDays(1); } default: return null; } }
From source file:org.apache.hadoop.hbase.util.Bytes.java
/** * Iterate over keys within the passed range. *//*from w w w . jav a 2s. c o m*/ public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be <= 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java
Object GetLargerValue(Object v) { byte type = DataType.findType(v); if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP) return null; switch (type) { case DataType.CHARARRAY: return (String) v + "0"; case DataType.BYTEARRAY: String str = ((DataByteArray) v).toString(); str = str + "0"; return new DataByteArray(str); case DataType.INTEGER: return Integer.valueOf((Integer) v + 1); case DataType.LONG: return Long.valueOf((Long) v + 1); case DataType.FLOAT: return Float.valueOf((Float) v + 1); case DataType.DOUBLE: return Double.valueOf((Double) v + 1); case DataType.BIGINTEGER: return ((BigInteger) v).add(BigInteger.ONE); case DataType.BIGDECIMAL: return ((BigDecimal) v).add(BigDecimal.ONE); case DataType.DATETIME: DateTime dt = (DateTime) v;//from ww w . j a v a 2s . c om if (dt.getMillisOfSecond() != 0) { return dt.plusMillis(1); } else if (dt.getSecondOfMinute() != 0) { return dt.plusSeconds(1); } else if (dt.getMinuteOfHour() != 0) { return dt.plusMinutes(1); } else if (dt.getHourOfDay() != 0) { return dt.plusHours(1); } else { return dt.plusDays(1); } default: return null; } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * /*from ww w . j a v a2 s .co m*/ */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:org.apache.kylin.common.util.Bytes.java
/** * Iterate over keys within the passed range. *///from w w w .j av a2 s .c om public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be <= 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1L); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.apache.pig.test.TestBuiltin.java
@Test public void testAVGIntermediate() throws Exception { String[] avgTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate", "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate", "BigIntegerAvgIntermediate" }; for (int k = 0; k < avgTypes.length; k++) { EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]); String inputType = getInputType(avgTypes[k]); Tuple tup = inputMap.get(inputType); // The tuple we got above has a bag with input // values. Input to the Intermediate.exec() however comes // from the map which would put each value and a count of // 1 in a tuple and send it down. So lets create a bag with // tuples that have two fields - the value and a count 1. DataBag bag = (DataBag) tup.get(0); DataBag bg = bagFactory.newDefaultBag(); for (Tuple t : bag) { Tuple newTuple = tupleFactory.newTuple(2); newTuple.set(0, t.get(0));/* ww w . j a va 2s . com*/ if (inputType == "BigDecimal") { newTuple.set(1, BigDecimal.ONE); } else if (inputType == "BigInteger") { newTuple.set(1, BigInteger.ONE); } else { newTuple.set(1, new Long(1)); } bg.add(newTuple); } Tuple intermediateInput = tupleFactory.newTuple(); intermediateInput.append(bg); Object output = avg.exec(intermediateInput); if (inputType == "Long" || inputType == "Integer" || inputType == "IntegerAsLong") { Long l = (Long) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + l + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, getExpected(avgTypes[k]), l); } else if (inputType == "BigDecimal") { BigDecimal f1 = (BigDecimal) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), f1.toPlainString()); } else if (inputType == "BigInteger") { BigInteger f1 = (BigInteger) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, ((BigInteger) getExpected(avgTypes[k])).toString(), f1.toString()); } else { Double f1 = (Double) ((Tuple) output).get(0); String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]"; assertEquals(msg, (Double) getExpected(avgTypes[k]), f1, 0.00001); } if (inputType == "BigDecimal") { BigDecimal f2 = (BigDecimal) ((Tuple) output).get(1); assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4", "4", f2.toPlainString()); } else if (inputType == "BigInteger") { BigInteger f2 = (BigInteger) ((Tuple) output).get(1); assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4", "4", f2.toString()); } else { Long f2 = (Long) ((Tuple) output).get(1); assertEquals( "[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 11", 11, f2.longValue()); } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic cosine.// w ww. j a v a2s .c om * * @param x The argument. * @return The cosh(x) = (exp(x)+exp(-x))/2 . */ static public BigDecimal cosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { if (x.doubleValue() > 1.5) { /* cosh^2(x) = 1+ sinh^2(x). */ return hypot(1, sinh(x)); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* 2i factorial */ BigInteger ifac = BigInteger.ONE; /* The absolute error in the result is the error in x^2/2 which is x times the error in x. */ double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); /* The error in the result is set by the error in x^2/2 itself, xUlpDbl. * We need at most k terms to push x^(2k)/(2k)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; /* The individual terms are all smaller than 1, so an estimate of 1.0 for * the absolute value will give a safe relative error estimate for the indivdual terms */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i-1 or 2*i overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); ifac = ifac.multiply(new BigInteger("" + (2 * i))); xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is governed by the error in x itself. */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } }