List of usage examples for com.google.common.math DoubleMath fuzzyEquals
public static boolean fuzzyEquals(double a, double b, double tolerance)
From source file:org.datavec.api.writable.DoubleWritable.java
public boolean fuzzyEquals(Writable o, double tolerance) { double other; if (o instanceof IntWritable) { other = ((IntWritable) o).toDouble(); } else if (o instanceof LongWritable) { other = ((LongWritable) o).toDouble(); } else if (o instanceof ByteWritable) { other = ((ByteWritable) o).toDouble(); } else if (o instanceof DoubleWritable) { other = ((DoubleWritable) o).toDouble(); } else if (o instanceof FloatWritable) { other = ((FloatWritable) o).toDouble(); } else {//from w w w. ja va2 s . c om return false; } return DoubleMath.fuzzyEquals(this.value, other, tolerance); }
From source file:org.onlab.graph.ScalarWeight.java
@Override public boolean equals(Object obj) { return ((obj instanceof ScalarWeight) && (DoubleMath.fuzzyEquals(value, ((ScalarWeight) obj).value, samenessThreshold))); }
From source file:com.opengamma.strata.math.impl.function.special.InverseIncompleteBetaFunction.java
@Override public Double apply(Double x) { ArgChecker.inRangeInclusive(x, 0d, 1d, "x"); double pp, p, t, h, w, lnA, lnB, u, a1 = _a - 1; double b1 = _b - 1; if (_a >= 1 && _b >= 1) { pp = x < 0.5 ? x : 1 - x;// w w w. ja v a 2 s. com t = Math.sqrt(-2 * Math.log(pp)); p = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t; if (p < 0.5) { p *= -1; } a1 = (Math.sqrt(p) - 3.) / 6.; double tempA = 1. / (2 * _a - 1); double tempB = 1. / (2 * _b - 1); h = 2. / (tempA + tempB); w = p * Math.sqrt(a1 + h) / h - (tempB - tempA) * (a1 + 5. / 6 - 2. / (3 * h)); p = _a / (_a + _b + Math.exp(2 * w)); } else { lnA = Math.log(_a / (_a + _b)); lnB = Math.log(_b / (_a + _b)); t = Math.exp(_a * lnA) / _a; u = Math.exp(_b * lnB) / _b; w = t + u; if (x < t / w) { p = Math.pow(_a * w * x, 1. / _a); } else { p = 1 - Math.pow(_b * w * (1 - x), 1. / _b); } } double afac = -_lnGamma.apply(_a) - _lnGamma.apply(_b) + _lnGamma.apply(_a + _b); double error; for (int j = 0; j < 10; j++) { if (DoubleMath.fuzzyEquals(p, 0d, 1e-16) || DoubleMath.fuzzyEquals(p, (double) 1, 1e-16)) { throw new MathException("a or b too small for accurate evaluation"); } error = _beta.apply(p) - x; t = Math.exp(a1 * Math.log(p) + b1 * Math.log(1 - p) + afac); u = error / t; t = u / (1 - 0.5 * Math.min(1, u * (a1 / p - b1 / (1 - p)))); p -= t; if (p <= 0) { p = 0.5 * (p + t); } if (p >= 1) { p = 0.5 * (p + t + 1); } if (Math.abs(t) < EPS * p && j > 0) { break; } } return p; }
From source file:com.opengamma.strata.math.impl.statistics.distribution.GeneralizedParetoDistribution.java
/** * //from w ww. ja v a2 s . co m * @param mu The location parameter * @param sigma The scale parameter * @param ksi The shape parameter * @param engine A uniform random number generator, not null */ public GeneralizedParetoDistribution(double mu, double sigma, double ksi, RandomEngine engine) { ArgChecker.isTrue(sigma > 0, "sigma must be > 0"); ArgChecker.isTrue(!DoubleMath.fuzzyEquals(ksi, 0d, 1e-15), "ksi cannot be zero"); ArgChecker.notNull(engine, "engine"); _mu = mu; _sigma = sigma; _ksi = ksi; _engine = engine; }
From source file:gobblin.source.extractor.extract.kafka.workunit.packer.KafkaSingleLevelWorkUnitPacker.java
@Override public List<WorkUnit> pack(Map<String, List<WorkUnit>> workUnitsByTopic, int numContainers) { setWorkUnitEstSizes(workUnitsByTopic); List<WorkUnit> workUnits = Lists.newArrayList(); for (List<WorkUnit> workUnitsForTopic : workUnitsByTopic.values()) { // For each topic, merge all empty workunits into a single workunit, so that a single // empty task will be created instead of many. MultiWorkUnit zeroSizeWorkUnit = MultiWorkUnit.createEmpty(); for (WorkUnit workUnit : workUnitsForTopic) { if (DoubleMath.fuzzyEquals(getWorkUnitEstSize(workUnit), 0.0, EPS)) { addWorkUnitToMultiWorkUnit(workUnit, zeroSizeWorkUnit); } else { workUnit.setWatermarkInterval(getWatermarkIntervalFromWorkUnit(workUnit)); workUnits.add(workUnit); }/* w w w. jav a2s .c o m*/ } if (!zeroSizeWorkUnit.getWorkUnits().isEmpty()) { workUnits.add(squeezeMultiWorkUnit(zeroSizeWorkUnit)); } } return worstFitDecreasingBinPacking(workUnits, numContainers); }
From source file:com.opengamma.strata.pricer.impl.option.BlackOneTouchCashPriceFormulaRepository.java
/** * Computes the price of a one-touch/no-touch option. * /*ww w . j a va 2s. co m*/ * @param spot the spot * @param timeToExpiry the time to expiry * @param costOfCarry the cost of carry * @param rate the interest rate * @param lognormalVol the lognormal volatility * @param barrier the barrier * @return the price */ public double price(double spot, double timeToExpiry, double costOfCarry, double rate, double lognormalVol, SimpleConstantContinuousBarrier barrier) { ArgChecker.notNull(barrier, "barrier"); boolean isKnockIn = barrier.getKnockType().isKnockIn(); boolean isDown = barrier.getBarrierType().isDown(); double h = barrier.getBarrierLevel(); ArgChecker.isFalse(isDown && spot <= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (DOWN and spot<=barrier)."); ArgChecker.isFalse(!isDown && spot >= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (UP and spot>=barrier)."); double eta = isDown ? 1 : -1; double df2 = Math.exp(-rate * timeToExpiry); double lognormalVolSq = lognormalVol * lognormalVol; double lognormalVolT = lognormalVol * Math.sqrt(timeToExpiry); if (DoubleMath.fuzzyEquals(Math.min(timeToExpiry, lognormalVolSq), 0d, SMALL)) { return isKnockIn ? 0d : df2; } double mu = (costOfCarry - 0.5 * lognormalVolSq) / lognormalVolSq; double lambda = Math.sqrt(mu * mu + 2 * rate / lognormalVolSq); double m1 = lognormalVolT * (1 + mu); double x2 = Math.log(spot / h) / lognormalVolT + m1; double y2 = Math.log(h / spot) / lognormalVolT + m1; double z = Math.log(h / spot) / lognormalVolT + lambda * lognormalVolT; double xE = isKnockIn ? getF(spot, z, lognormalVolT, h, mu, lambda, eta) : getE(spot, df2, x2, y2, lognormalVolT, h, mu, eta); return xE; }
From source file:com.opengamma.strata.pricer.impl.option.BlackOneTouchAssetPriceFormulaRepository.java
/** * Computes the price of a one-touch/no-touch option. * /*from w w w . ja v a 2 s .c om*/ * @param spot the spot * @param timeToExpiry the time to expiry * @param costOfCarry the cost of carry * @param rate the interest rate * @param lognormalVol the lognormal volatility * @param barrier the barrier * @return the price */ public double price(double spot, double timeToExpiry, double costOfCarry, double rate, double lognormalVol, SimpleConstantContinuousBarrier barrier) { ArgChecker.notNull(barrier, "barrier"); boolean isKnockIn = barrier.getKnockType().isKnockIn(); boolean isDown = barrier.getBarrierType().isDown(); double h = barrier.getBarrierLevel(); ArgChecker.isFalse(isDown && spot <= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (DOWN and spot<=barrier)."); ArgChecker.isFalse(!isDown && spot >= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (UP and spot>=barrier)."); double eta = isDown ? 1 : -1; double df1 = Math.exp(timeToExpiry * (costOfCarry - rate)); double lognormalVolSq = lognormalVol * lognormalVol; double lognormalVolT = lognormalVol * Math.sqrt(timeToExpiry); if (DoubleMath.fuzzyEquals(Math.min(timeToExpiry, lognormalVolSq), 0d, SMALL)) { return isKnockIn ? 0d : spot * df1; } double mu = (costOfCarry - 0.5 * lognormalVolSq) / lognormalVolSq; double lambda = Math.sqrt(mu * mu + 2 * rate / lognormalVolSq); double m1 = lognormalVolT * (1 + mu); double x2 = Math.log(spot / h) / lognormalVolT + m1; double y2 = Math.log(h / spot) / lognormalVolT + m1; double z = Math.log(h / spot) / lognormalVolT + lambda * lognormalVolT; double xE = isKnockIn ? getF(spot, z, lognormalVolT, h, mu, lambda, eta, h) : getE(spot, df1, x2, y2, h, mu, eta); return xE; }
From source file:com.ibm.og.util.Distributions.java
/** * Creates a lognormal distribution./*from w w w. j a v a 2 s . co m*/ * * @param average the average * @param spread the spread * @return a lognormal distribution instance * @throws IllegalArgumentException if average or spread are negative, or if average - 3*spread is * negative */ public static Distribution lognormal(final double average, final double spread) { // FIXME configure lognormal distribution range correctly checkArgument(average >= 0.0, "average must be >= 0.0 [%s]", average); checkArgument(spread >= 0.0, "spread must be >= 0.0 [%s]", spread); if (DoubleMath.fuzzyEquals(spread, 0.0, Distributions.ERR)) { return constant(average); } final double min = average - (3 * spread); checkArgument(min >= 0.0, "three standard deviations must be >= 0.0 [%s]", min); final String s = String.format("LogNormalDistribution [average=%s, spread=%s]", average, spread); return new RealDistributionAdapter(new LogNormalDistribution(average, spread), s); }
From source file:com.opengamma.strata.pricer.impl.option.BlackBarrierPriceFormulaRepository.java
/** * Computes the price of a barrier option. * // w w w . j a va2 s . c om * @param spot the spot * @param strike the strike * @param timeToExpiry the time to expiry * @param costOfCarry the cost of carry * @param rate the interest rate * @param lognormalVol the lognormal volatility * @param isCall true if call, false otherwise * @param barrier the barrier * @return the price */ public double price(double spot, double strike, double timeToExpiry, double costOfCarry, double rate, double lognormalVol, boolean isCall, SimpleConstantContinuousBarrier barrier) { ArgChecker.notNull(barrier, "barrier"); boolean isKnockIn = barrier.getKnockType().isKnockIn(); boolean isDown = barrier.getBarrierType().isDown(); double h = barrier.getBarrierLevel(); ArgChecker.isFalse(isDown && spot <= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (DOWN and spot<=barrier)."); ArgChecker.isFalse(!isDown && spot >= barrier.getBarrierLevel(), "The Data is not consistent with an alive barrier (UP and spot>=barrier)."); int phi = isCall ? 1 : -1; double eta = isDown ? 1 : -1; double df1 = Math.exp(timeToExpiry * (costOfCarry - rate)); double df2 = Math.exp(-rate * timeToExpiry); double sigmaSq = lognormalVol * lognormalVol; double sigmaT = lognormalVol * Math.sqrt(timeToExpiry); if (DoubleMath.fuzzyEquals(Math.min(timeToExpiry, sigmaSq), 0d, SMALL)) { if (isKnockIn) { return 0d; } double dscFwd = df1 * spot; double dscStr = df2 * strike; return isCall ? (dscFwd >= dscStr ? dscFwd - dscStr : 0d) : (dscStr >= dscFwd ? dscStr - dscFwd : 0d); } double mu = (costOfCarry - 0.5 * sigmaSq) / sigmaSq; double m1 = sigmaT * (1 + mu); double x1 = Math.log(spot / strike) / sigmaT + m1; double x2 = Math.log(spot / h) / sigmaT + m1; double y1 = Math.log(h * h / spot / strike) / sigmaT + m1; double y2 = Math.log(h / spot) / sigmaT + m1; double xA = getA(spot, strike, df1, df2, x1, sigmaT, phi); double xB = getA(spot, strike, df1, df2, x2, sigmaT, phi); double xC = getC(spot, strike, df1, df2, y1, sigmaT, h, mu, phi, eta); double xD = getC(spot, strike, df1, df2, y2, sigmaT, h, mu, phi, eta); if (isKnockIn) { // KnockIn if (isDown) { if (isCall) { return strike > h ? xC : xA - xB + xD; } return strike > h ? xB - xC + xD : xA; } if (isCall) { return strike > h ? xA : xB - xC + xD; } return strike > h ? xA - xB + xD : xC; } // KnockOut if (isDown) { if (isCall) { return strike > h ? xA - xC : xB - xD; } return strike > h ? xA - xB + xC - xD : 0d; } if (isCall) { return strike > h ? 0d : xA - xB + xC - xD; } return strike > h ? xB - xD : xA - xC; }
From source file:ucar.nc2.ogc.erddap.util.ErddapEDUnits.java
/** * This converts UDUnits to UCUM.//from ww w . jav a2 s .c om * <br>UDUnits: http://www.unidata.ucar.edu/software/udunits/udunits-1/etc/udunits.dat * http://www.unidata.ucar.edu/software/udunits/udunits-2/udunits2.html * I worked with v 2.1.9 * <br>UCUM: http://unitsofmeasure.org/ucum.html * I worked with Version: 1.8, $Revision: 28894 $ * <p/> * <p>UDUnits supports lots of aliases (short and long) * and plurals (usually by adding 's'). * These all get reduced to UCUM's short and canonical-only units. * <p/> * <p>Notes: * <ul> * <li>This method is a strictly case sensitive. * The only UDUnits that should be capitalized (other than acronyms) are * Btu, Gregorian..., Julian..., PI. * <br>The only UDUnits that may be capitalized are * Celsius, Fahrenheit, Kelvin, Rankine. * <li>For "10 to the", UCUM allows 10* or 10^. This method uses 10^. * <li>NTU becomes {ntu}. * <li>PSU or psu becomes {psu}. * </ul> * <p/> * return the UDUnits converted to UCUM. * null returns null. "" returns "". * throws Exception if trouble. */ public static String udunitsToUcum(String udunits) { if (udunits == null) { return null; } //is it a point in time? e.g., seconds since 1970-01-01T00:00:00T int sincePo = udunits.indexOf(" since "); if (sincePo > 0) { try { //test if really appropriate double baf[] = ErddapCalendar2.getTimeBaseAndFactor(udunits); //throws exception if trouble //use 'factor', since it is more forgiving than udunitsToUcum converter String u; if (DoubleMath.fuzzyEquals(baf[1], 0.001, 1e-6)) { // Can't simply do "baf[1] == 0.001". u = "ms"; } else if (baf[1] == 1) { u = "s"; } else if (baf[1] == ErddapCalendar2.SECONDS_PER_MINUTE) { u = "min"; } else if (baf[1] == ErddapCalendar2.SECONDS_PER_HOUR) { u = "h"; } else if (baf[1] == ErddapCalendar2.SECONDS_PER_DAY) { u = "d"; } else if (baf[1] == 30 * ErddapCalendar2.SECONDS_PER_DAY) { // mo_j ? u = "mo"; } else if (baf[1] == 360 * ErddapCalendar2.SECONDS_PER_DAY) { // a_j ? u = "a"; } else { u = udunitsToUcum(udunits.substring(0, sincePo)); //shouldn't happen, but weeks? microsec? } //make "s{since 1970-01-01T00:00:00T} return u + "{" + udunits.substring(sincePo + 1) + "}"; } catch (Exception e) { } } //parse udunits and build ucum, till done StringBuilder ucum = new StringBuilder(); int udLength = udunits.length(); int po = 0; //po is next position to be read while (po < udLength) { char ch = udunits.charAt(po); //letter if (isUdunitsLetter(ch)) { //includes '' and '' //find contiguous letters|_|digit (no '-') int po2 = po + 1; while (po2 < udLength && (isUdunitsLetter(udunits.charAt(po2)) || udunits.charAt(po2) == '_' || ErddapString2.isDigit(udunits.charAt(po2)))) { po2++; } String tUdunits = udunits.substring(po, po2); po = po2; //some udunits have internal digits, but none end in digits //if it ends in digits, treat as exponent //find contiguous digits at end int firstDigit = tUdunits.length(); while (firstDigit >= 1 && ErddapString2.isDigit(tUdunits.charAt(firstDigit - 1))) { firstDigit--; } String exponent = tUdunits.substring(firstDigit); tUdunits = tUdunits.substring(0, firstDigit); String tUcum = oneUdunitsToUcum(tUdunits); //deal with PER -> / if (tUcum.equals("/")) { char lastUcum = ucum.length() == 0 ? '\u0000' : ucum.charAt(ucum.length() - 1); if (lastUcum == '/') { ucum.setCharAt(ucum.length() - 1, '.'); //2 '/' cancel out } else if (lastUcum == '.') { ucum.setCharAt(ucum.length() - 1, '/'); // '/' replaces '.' } else { ucum.append('/'); } } else { ucum.append(tUcum); } //add the exponent ucum.append(exponent); //catch -exponent as a number below continue; } //number if (ch == '-' || ErddapString2.isDigit(ch)) { //find contiguous digits int po2 = po + 1; while (po2 < udLength && ErddapString2.isDigit(udunits.charAt(po2))) { po2++; } //decimal place + digit (not just .=multiplication) boolean hasDot = false; if (po2 < udLength - 1 && udunits.charAt(po2) == '.' && ErddapString2.isDigit(udunits.charAt(po2 + 1))) { hasDot = true; po2 += 2; while (po2 < udLength && ErddapString2.isDigit(udunits.charAt(po2))) { po2++; } } //exponent? e- or e{digit} boolean hasE = false; if (po2 < udLength - 1 && Character.toLowerCase(udunits.charAt(po2)) == 'e' && (udunits.charAt(po2 + 1) == '-' || ErddapString2.isDigit(udunits.charAt(po2 + 1)))) { hasE = true; po2 += 2; while (po2 < udLength && ErddapString2.isDigit(udunits.charAt(po2))) { po2++; } } String num = udunits.substring(po, po2); po = po2; //convert floating point to rational number if (hasDot || hasE) { int rational[] = ErddapString2.toRational(ErddapString2.parseDouble(num)); if (rational[1] == Integer.MAX_VALUE) { ucum.append(num); //ignore the trouble !!! ??? } else if (rational[1] == 0) //includes {0, 0} { ucum.append(rational[0]); } else { ucum.append(rational[0]).append(".10^").append(rational[1]); } } else { //just copy num ucum.append(num); } continue; } //space or . or (183) (multiplication) if (ch == ' ' || ch == '.' || ch == 183) { char lastUcum = ucum.length() == 0 ? '\u0000' : ucum.charAt(ucum.length() - 1); if (lastUcum == '/' || lastUcum == '.') { //if last token was / or ., do nothing } else { ucum.append('.'); } po++; continue; } // * (multiplication * or exponent **) if (ch == '*') { po++; if (po < udLength && udunits.charAt(po) == '*') { ucum.append('^'); // exponent: ** -> ^ po++; } else { char lastUcum = ucum.length() == 0 ? '\u0000' : ucum.charAt(ucum.length() - 1); if (lastUcum == '/' || lastUcum == '.') { //if last token was / or ., do nothing } else { ucum.append('.'); } } continue; } // / if (ch == '/') { po++; char lastUcum = ucum.length() == 0 ? '\u0000' : ucum.charAt(ucum.length() - 1); if (lastUcum == '/') { ucum.setCharAt(ucum.length() - 1, '.'); // 2 '/' cancel out } else if (lastUcum == '.') { ucum.setCharAt(ucum.length() - 1, '/'); // '/' replaces '.' } else { ucum.append('/'); } continue; } // " if (ch == '\"') { po++; ucum.append("''"); continue; } //otherwise, punctuation. copy it ucum.append(ch); po++; } return ucum.toString(); }