List of usage examples for java.math BigInteger multiply
BigInteger multiply(long v)
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. *//*www. ja v a 2 s. 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.kylin.common.util.Bytes.java
/** * Iterate over keys within the passed range. *///from w w w . jav 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.hadoop.hbase.util.Bytes.java
/** * Iterate over keys within the passed range. *///w w w.j a v a2s .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 + 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.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java
@Override protected void readImpl() throws BufferUnderflowException, RuntimeException { readC();// w w w . j a va 2s . com if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) { final SecureRandom random = new SecureRandom(); MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return; } final BigInteger k = new BigInteger("3"); final byte[] Bb = readB(32); final BigInteger g = new BigInteger(readB(readC())); final byte[] Nb = readB(readC()); final byte[] saltb = readB(32); /* byte[] unk3 = */readB(16); readC(); ArrayUtils.reverse(Bb); final BigInteger B = new BigInteger(1, Bb); ArrayUtils.reverse(Bb); ArrayUtils.reverse(Nb); final BigInteger N = new BigInteger(1, Nb); ArrayUtils.reverse(Nb); final BigInteger a = new BigInteger(1, random.generateSeed(19)); final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":") .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8"))); sha.update(saltb); sha.update(passhash); final byte[] xhash = sha.digest(); ArrayUtils.reverse(xhash); final BigInteger x = new BigInteger(1, xhash); logger.debug("x:" + x.toString(16).toUpperCase()); final BigInteger v = g.modPow(x, N); logger.debug("v:" + v.toString(16).toUpperCase()); final BigInteger A = g.modPow(a, N); logger.debug("A:" + A.toString(16).toUpperCase()); logger.debug("B:" + B.toString(16).toUpperCase()); this.ahash = A.toByteArray(); ArrayUtils.reverse(this.ahash); sha.update(this.ahash); sha.update(Bb); final byte[] hashu = sha.digest(); ArrayUtils.reverse(hashu); final BigInteger u = new BigInteger(1, hashu); logger.debug("u:" + u.toString(16).toUpperCase()); final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N); final byte[] full_S = S.toByteArray(); ArrayUtils.reverse(full_S); logger.debug("t:" + StringUtils.toHexString(full_S)); final byte[] s1_hash = new byte[16]; final byte[] s2_hash = new byte[16]; for (int i = 0; i < 16; i++) { s1_hash[i] = full_S[i * 2]; s2_hash[i] = full_S[(i * 2) + 1]; } final byte[] t1 = sha.digest(s1_hash); final byte[] t2 = sha.digest(s2_hash); final byte[] vK = new byte[40]; for (int i = 0; i < 20; i++) { vK[i * 2] = t1[i]; vK[(i * 2) + 1] = t2[i]; } byte[] hash = new byte[20]; logger.debug("N:" + N.toString(16).toUpperCase()); hash = sha.digest(Nb); logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase()); byte[] gH = new byte[20]; sha.update(g.toByteArray()); gH = sha.digest(); for (int i = 0; i < 20; ++i) { hash[i] ^= gH[i]; } byte[] t4 = new byte[20]; t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8"))); sha.update(hash); logger.debug("hash:" + StringUtils.toHexString(hash)); sha.update(t4); logger.debug("t4:" + StringUtils.toHexString(t4)); sha.update(saltb); logger.debug("saltb:" + StringUtils.toHexString(saltb)); sha.update(this.ahash); logger.debug("ahash:" + StringUtils.toHexString(this.ahash)); sha.update(Bb); logger.debug("Bb:" + StringUtils.toHexString(Bb)); sha.update(vK); logger.debug("vK:" + StringUtils.toHexString(vK)); this.m1 = sha.digest(); sha.update(this.ahash); sha.update(this.m1); sha.update(vK); logger.debug("m1 value" + StringUtils.toHexString(this.m1)); @SuppressWarnings("unused") final byte[] m2 = sha.digest(); final ChannelPipeline pipeline = getClient().getChannel().getPipeline(); ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK); } else { getChannel().getPipeline().remove("handler"); getChannel().getPipeline().remove("eventlog"); getChannel().getPipeline().remove("executor"); getChannel().close(); getChannel().getFactory().releaseExternalResources(); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Trigonometric cosine.//from w ww . j a v a 2 s .c om * * @param x The argument in radians. * @return cos(x) in the range -1 to 1. */ static public BigDecimal cos(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { /* reduce modulo 2pi */ BigDecimal res = mod2pi(x); double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); int val = +err2prec(FastMath.PI, errpi); MathContext mc = new MathContext(val); BigDecimal p = pi(mc); mc = new MathContext(x.precision()); if (res.compareTo(p) > 0) { /* pi<x<=2pi: cos(x)= - cos(x-pi) */ return cos(subtractRound(res, p)).negate(); } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) { /* pi/2<x<=pi: cos(x)= -cos(pi-x) */ return cos(subtractRound(p, res)).negate(); } else { /* for the range 0<=x<Pi/2 one could use cos(2x)= 1-2*sin^2(x) * to split this further, or use the cos up to pi/4 and the sine higher up. throw new ProviderException("Unimplemented cosine ") ; */ if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { /* x>pi/4: cos(x) = sin(pi/2-x) */ return sin(subtractRound(p.divide(new BigDecimal("2")), res)); } else { /* Simple Taylor expansion, sum_{i=0..infinity} (-1)^(..)res^(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 * res.ulp().doubleValue() * res.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+1)/(2k+1)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2; 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(res).multiply(res).negate(); 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. */ mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic sine./*from w ww . ja v a 2 s. c o m*/ * * @param x the argument. * @return the sinh(x) = (exp(x)-exp(-x))/2 . */ static public BigDecimal sinh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return sinh(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { if (x.doubleValue() > 2.4) { /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x). */ BigDecimal two = new BigDecimal(2); BigDecimal xhalf = x.divide(two); BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two); /* The error in the result is set by the error in x itself. * The first derivative of sinh(x) is cosh(x), so the absolute error * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x) */ double eps = Math.tanh(x.doubleValue()); MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps)); return resul.round(mc); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */ BigDecimal resul = xhighpr; /* x^i */ BigDecimal xpowi = xhighpr; /* 2i+1 factorial */ BigInteger ifac = BigInteger.ONE; /* The error in the result is set by the error in x itself. */ double xUlpDbl = x.ulp().doubleValue(); /* The error in the result is set by the error in x itself. * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value. * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision; * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision */ int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i or 2*i+1 overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i))); ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); 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 set by the error in x itself. */ MathContext mc = new MathContext(x.precision()); return resul.round(mc); } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Trigonometric sine.//from w w w . ja v a2 s . c o m * * @param x The argument in radians. * @return sin(x) in the range -1 to 1. */ static public BigDecimal sin(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return sin(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { /* reduce modulo 2pi */ BigDecimal res = mod2pi(x); double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); int val = 2 + err2prec(FastMath.PI, errpi); MathContext mc = new MathContext(val); BigDecimal p = pi(mc); mc = new MathContext(x.precision()); if (res.compareTo(p) > 0) { /* pi<x<=2pi: sin(x)= - sin(x-pi) */ return sin(subtractRound(res, p)).negate(); } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) { /* pi/2<x<=pi: sin(x)= sin(pi-x) */ return sin(subtractRound(p, res)); } else { /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x) * to split this further. Here, use the sine up to pi/4 and the cosine higher up. */ if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { /* x>pi/4: sin(x) = cos(pi/2-x) */ return cos(subtractRound(p.divide(new BigDecimal("2")), res)); } else { /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */ BigDecimal resul = res; /* x^i */ BigDecimal xpowi = res; /* 2i+1 factorial */ BigInteger ifac = BigInteger.ONE; /* The error in the result is set by the error in x itself. */ double xUlpDbl = res.ulp().doubleValue(); /* The error in the result is set by the error in x itself. * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value. * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision; * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision */ int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i or 2*i+1 overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i))); ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); xpowi = xpowi.multiply(res).multiply(res).negate(); 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 set by the error in x itself. */ mc = new MathContext(res.precision()); return resul.round(mc); } } } /* sin */ }
From source file:com.udojava.evalex.Expression.java
/** * Creates a new expression instance from an expression string with a given * default match context./*from w w w . ja v a 2 s.c o m*/ * * @param expression The expression. E.g. <code>"2.4*sin(3)/(2-4)"</code> or * <code>"sin(y)>0 & max(z, 3)>3"</code> */ public Expression(String expression, LinkedList<String> hist, Variables vars) { this.history = hist; this.expression = expression; mainVars = vars; addOperator(new Operator("+", 20, true, "Addition") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.add(v2); return vo; } return v1.add(v2); } }); addOperator(new Operator("-", 20, true, "Subtraction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.removeIf(o -> o.equals(v2)); return vo; } return v1.subtract(v2); } }); addOperator(new Operator("*", 30, true, "Real number multiplication") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.multiply(v2); } }); addOperator(new Operator("/", 30, true, "Real number division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.divide(v2); } }); addOperator(new Operator("%", 30, true, "Remainder of integer division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { double r = v1.real % v2.real; return new MyComplex(r); } }); addOperator( new Operator("^", 40, false, "Exponentation. See: https://en.wikipedia.org/wiki/Exponentiation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.pow(v2); } }); addOperator(new Operator("&&", 4, false, "Logical AND. Evaluates to 1 if both operands are not 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 1 : 0); } }); addOperator(new Operator("||", 2, false, "Logical OR. Evaluates to 0 if both operands are 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 0 : 1); } }); addOperator(new Operator(">", 10, false, "Greater than. See: See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real > v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() > v2.abs() ? 1 : 0); } } }); addOperator(new Operator(">=", 10, false, "Greater or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real >= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() >= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<", 10, false, "Less than. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real < v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() < v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<=", 10, false, "less or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real <= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() <= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("->", 7, false, "Set variable v to new value ") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1 instanceof PitDecimal) { PitDecimal target = (PitDecimal) v1; String s = target.getVarToken(); setVariable(s, v2); return v2; } throw new ExpressionException("LHS not variable"); } }); addOperator(new Operator("=", 7, false, "Equality") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real == v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() == v2.abs() ? 1 : 0); } } }); addOperator(new Operator("!=", 7, false, "Inequality. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real != v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() != v2.abs() ? 1 : 0); } } }); addOperator( new Operator("or", 7, false, "Bitwise OR. See: https://en.wikipedia.org/wiki/Logical_disjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real | (long) v2.real); } }); addOperator(new Operator("and", 7, false, "Bitwise AND. See: https://en.wikipedia.org/wiki/Logical_conjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real & (long) v2.real); } }); addOperator(new Operator("xor", 7, false, "Bitwise XOR, See: https://en.wikipedia.org/wiki/Exclusive_or") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real ^ (long) v2.real); } }); addOperator(new Operator("!", 50, true, "Factorial. See https://en.wikipedia.org/wiki/Factorial") { public BigInteger factorial(long n) { BigInteger factorial = BigInteger.ONE; for (long i = 1; i <= n; i++) { factorial = factorial.multiply(BigInteger.valueOf(i)); } return factorial; } @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger fact = factorial((long) v1.real); return new MyComplex(fact, BigInteger.ZERO); } }); addOperator(new Operator("~", 8, false, "Bitwise negation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger bi = v2.toBigIntegerReal(); int c = bi.bitLength(); if (c == 0) { return new MyComplex(1); } for (int s = 0; s < c; s++) { bi = bi.flipBit(s); } return new MyComplex(bi); } }); addOperator(new Operator("shl", 8, false, "Left Bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real << (long) v2.real); } }); addOperator(new Operator("shr", 8, false, "Right bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real >>> (long) v2.real); } }); addFunction(new Function("NOT", 1, "evaluates to 0 if argument != 0") { @Override public MyComplex eval(List<MyComplex> parameters) { boolean zero = parameters.get(0).abs() == 0; return new MyComplex(zero ? 1 : 0); } }); addFunction(new Function("RND", 2, "Give random number in the range between first and second argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double low = parameters.get(0).real; double high = parameters.get(1).real; return new MyComplex(low + Math.random() * (high - low)); } }); MersenneTwister mers = new MersenneTwister(System.nanoTime()); addFunction(new Function("MRS", 0, "Mersenne twister random generator") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(mers.nextDouble()); } }); addFunction(new Function("BIN", 2, "Binomial Coefficient 'n choose k'") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.binomialCoefficientDouble(n, k); return new MyComplex(d); } }); addFunction(new Function("STIR", 2, "Stirling number of 2nd kind: http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.stirlingS2(n, k); return new MyComplex(d); } }); addFunction(new Function("SIN", 1, "Sine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sin(); } }); addFunction(new Function("COS", 1, "Cosine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cos(); } }); addFunction(new Function("TAN", 1, "Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tan(); } }); addFunction(new Function("ASIN", 1, "Reverse Sine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).asin(); } }); addFunction(new Function("ACOS", 1, "Reverse Cosine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).acos(); } }); addFunction(new Function("ATAN", 1, "Reverse Tangent") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).atan(); } }); addFunction(new Function("SINH", 1, "Hyperbolic Sine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sinh(); } }); addFunction(new Function("COSH", 1, "Hyperbolic Cosine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cosh(); } }); addFunction(new Function("TANH", 1, "Hyperbolic Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tanh(); } }); addFunction(new Function("RAD", 1, "Transform degree to radian") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toRadians(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("DEG", 1, "Transform radian to degree") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toDegrees(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("MAX", -1, "Find the biggest value in a list") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MIN_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } // if (parameters.get(0).type == ValueType.ARRAY) // parameters = parameters.get(0).list; if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() > save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real > save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); /////////////////////////////////////////////////////// addFunction(new Function("IF", 3, "Conditional: give param3 if param1 is 0, otherwise param2") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).real == 0.0) { return parameters.get(2); } return parameters.get(1); } }); addFunction(new Function("PERC", 2, "Get param1 percent of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).divide(new MyComplex(100)).multiply(parameters.get(1)); } }); addFunction(new Function("PER", 2, "How many percent is param1 of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).multiply(new MyComplex(100)).divide(parameters.get(1)); } }); addFunction(new Function("H", 1, "Evaluate _history element") { @Override public MyComplex eval(List<MyComplex> parameters) { int i = (int) parameters.get(0).real; Expression ex = new Expression(history.get(i), history, mainVars); return ex.eval(); } }); addFunction(new Function("MERS", 1, "Calculate Mersenne Number") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); return new MyComplex(2).pow(p).subtract(new MyComplex(1)); } }); addFunction(new Function("GCD", 2, "Find greatest common divisor of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.gcd((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("LCM", 2, "Find least common multiple of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.lcm((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("AMEAN", -1, "Arithmetic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } Mean m = new Mean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); // addFunction(new Function("BYT", -1, // "Value from sequence of bytes") // { // @Override // public MyComplex eval (List<MyComplex> parameters) // { // if (parameters.size() == 0) // { // return MyComplex.ZERO; // } // BigInteger res = BigInteger.ZERO; // for (MyComplex parameter : parameters) // { // if (parameter.intValue() < 0 || parameter.intValue() > 255) // { // throw new ExpressionException("not a byte value"); // } // res = res.shiftLeft(8); // res = res.or(parameter.toBigInteger()); // } // return new MyComplex(res, BigInteger.ZERO); // } // }); addFunction(new Function("SEQ", 3, "Generate Sequence p1=start, p2=step, p3=count") { @Override public MyComplex eval(List<MyComplex> parameters) { double start = parameters.get(0).real; ArrayList<MyComplex> arr = new ArrayList<>(); for (int s = 0; s < (int) (parameters.get(2).real); s++) { arr.add(new MyComplex(start)); start += parameters.get(1).real; } return new MyComplex(arr); } }); addFunction(new Function("PROD", -1, "Product of real values") { @Override public MyComplex eval(List<MyComplex> parameters) { Product p = new Product(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("SUM", -1, "Sum of values") { @Override public MyComplex eval(List<MyComplex> parameters) { Sum p = new Sum(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("ANG", 1, "Angle phi of complex number in radians") { @Override public MyComplex eval(List<MyComplex> parameters) { double b = parameters.get(0).angle(); return new MyComplex(b); } }); addFunction(new Function("IM", 1, "Get imaginary part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).imaginary); } }); addFunction(new Function("RE", 1, "Get real part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).real); } }); addFunction(new Function("POL", 2, "Make complex number from polar coords. angle is first arg") { @Override public MyComplex eval(List<MyComplex> parameters) { double angle = parameters.get(0).real; double len = parameters.get(1).real; Complex c = ComplexUtils.polar2Complex(len, angle); return new MyComplex(c); } }); addFunction(new Function("GMEAN", -1, "Geometric mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } GeometricMean m = new GeometricMean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); addFunction(new Function("HMEAN", -1, "Harmonic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } MyComplex res = new MyComplex(0); int num = 0; for (MyComplex parameter : parameters) { res = res.add(new MyComplex(1).divide(parameter)); num++; } res = new MyComplex(res.abs()); return new MyComplex(num).divide(res); } }); addFunction(new Function("VAR", -1, "Variance of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } double[] arr = new double[parameters.size()]; for (int s = 0; s < parameters.size(); s++) { arr[s] = parameters.get(s).real; } return new MyComplex(variance(arr)); } }); addFunction(new Function("NPR", 1, "Next prime number greater or equal the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(nextPrime((int) parameters.get(0).real)); } }); addFunction(new Function("NSWP", 1, "Swap nibbles") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); s = new StringBuilder(s).reverse().toString(); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("BSWP", 1, "Swap bytes") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); while (s.length() % 4 != 0) { s = s + "0"; } if (bi.intValue() < 256) { s = "00" + s; } s = Misc.reverseHex(s); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("PYT", 2, "Pythagoras's result = sqrt(param1^2+param2^2) https://en.wikipedia.org/wiki/Pythagorean_theorem") { @Override public MyComplex eval(List<MyComplex> par) { double a = par.get(0).real; double b = par.get(1).real; return new MyComplex(Math.sqrt(a * a + b * b)); } }); addFunction(new Function("FIB", 1, "Fibonacci number") { // --Commented out by Inspection (2/19/2017 7:46 PM):private final Operator exp = operators.get("^"); @Override public MyComplex eval(List<MyComplex> par) { return Misc.iterativeFibonacci((int) par.get(0).real); } }); /////////////////////////////////////////////// addFunction(new Function("MIN", -1, "Find the smallest in a list of values") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MAX_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() < save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real < save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); addFunction(new Function("ABS", 1, "Get absolute value of a number") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).abs()); } }); addFunction(new Function("LN", 1, "Logarithm base e of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("LOG", 1, "Logarithm base 10 of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log10(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("FLOOR", 1, "Rounds DOWN to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.floor(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("CEIL", 1, "Rounds UP to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.ceil(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("ROU", 1, "Rounds to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { int d = (int) (parameters.get(0).real + 0.5); return new MyComplex(d); } }); addFunction(new Function("SQRT", 1, "Square root") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); if (p.type == ValueType.REAL) { return new MyComplex(Math.sqrt(p.real)); } return p.sqrt(); } }); addFunction(new Function("ARR", -1, "Create array") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters); } }); addFunction(new Function("POLY", -1, "Treat array as Polynom") { @Override public MyComplex eval(List<MyComplex> parameters) { double[] d = MyComplex.getRealArray(parameters); PolynomialFunction p = new PolynomialFunction(d); return new MyComplex(p); } }); addFunction(new Function("DRVE", -1, "Make derivative of polynomial") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(p.polynomialDerivative()); } }); addFunction(new Function("ADRVE", -1, "Make antiderivative of polynomial. Constant is always zero") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(Misc.antiDerive(p)); } }); addFunction(new Function("PVAL", 2, "Compute value of polynom for the given argument.") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double v = p.value(parameters.get(1).real); return new MyComplex(v); } throw new ExpressionException("first arg must be polynomial"); } }); addFunction(new Function("INTGR", 3, "Numerical integration") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double start = parameters.get(1).real; double end = parameters.get(2).real; SimpsonIntegrator si = new SimpsonIntegrator(); double d = si.integrate(1000, p, start, end); return new MyComplex(d); } throw new ExpressionException("first arg must be polynomial"); } }); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic cosine.//ww w . j av a 2s . c o m * * @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); } } }
From source file:net.pms.util.Rational.java
/** * Returns a {@link Rational} whose value is {@code (this + value)}. * * @param value the value to be added to this {@link Rational}. * @return The addition result.// w w w . j a va2s. c o m */ @Nullable public Rational add(@Nullable BigInteger value) { if (value == null) { return null; } if (isNaN()) { return NaN; } if (isInfinite() || value.signum() == 0) { return this; } if (BigInteger.ONE.equals(denominator)) { return valueOf(numerator.add(value), denominator); } return valueOf(numerator.add(value.multiply(denominator)), denominator); }