List of usage examples for com.google.common.math DoubleMath fuzzyEquals
public static boolean fuzzyEquals(double a, double b, double tolerance)
From source file:com.ibm.og.test.SimpleRequestManager.java
/** * Creates an instance. This manager determines which type of request to generate based on the * provided weights for each request type. * //from w w w .j a va 2 s . c o m * @param write a supplier of write requests * @param writeWeight percentage of the time that a write request should be generated * @param read a supplier of read requests * @param readWeight percentage of the time that a read request should be generated * @param delete a supplier of delete requests * @param deleteWeight percentage of the time that a delete request should be generated * @param metadata a supplier of metadata (HEAD) requests * @param metadataWeight percentage of the time that a metadata (HEAD) request should be generated * @throws NullPointerException if write, read, or delete are null * @throws IllegalArgumentException if writeWeight, readWeight, or deleteWeight are not in the * range [0.0, 100.0], or if the sum of the individual weights is not 100.0 */ @Inject @Singleton public SimpleRequestManager(@Named("write") final Supplier<Request> write, @Named("write.weight") final double writeWeight, @Named("overwrite") final Supplier<Request> overwrite, @Named("overwrite.weight") final double overwriteWeight, @Named("read.weight") final double readWeight, @Named("read") final Supplier<Request> read, @Named("metadata") final Supplier<Request> metadata, @Named("metadata.weight") final double metadataWeight, @Named("delete") final Supplier<Request> delete, @Named("delete.weight") final double deleteWeight, @Named("list") final Supplier<Request> list, @Named("list.weight") final double listWeight, @Named("containerList") final Supplier<Request> containerList, @Named("containerList.weight") final double containerListWeight, @Named("containerCreate") final Supplier<Request> containerCreate, @Named("containerCreate.weight") final double containerCreateWeight, @Named("multipartWrite") final Supplier<Request> writeMultipart, @Named("multipartWrite.weight") final double writeMultipartWeight) { checkNotNull(write); checkNotNull(overwrite); checkNotNull(read); checkNotNull(metadata); checkNotNull(delete); checkNotNull(list); checkNotNull(containerList); checkNotNull(containerCreate); checkNotNull(writeMultipart); checkArgument(PERCENTAGE.contains(writeWeight), "write weight must be in range [0.0, 100.0] [%s]", writeWeight); checkArgument(PERCENTAGE.contains(overwriteWeight), "overwrite weight must be in range [0.0, 100.0] [%s]", overwriteWeight); checkArgument(PERCENTAGE.contains(readWeight), "read weight must be in range [0.0, 100.0] [%s]", readWeight); checkArgument(PERCENTAGE.contains(metadataWeight), "delete weight must be in range [0.0, 100.0] [%s]", metadataWeight); checkArgument(PERCENTAGE.contains(deleteWeight), "delete weight must be in range [0.0, 100.0] [%s]", deleteWeight); checkArgument(PERCENTAGE.contains(listWeight), "list weight must be in range [0.0, 100.0] [%s]", listWeight); checkArgument(PERCENTAGE.contains(containerListWeight), "containerList weight must be in range [0.0, 100.0] [%s]", containerListWeight); checkArgument(PERCENTAGE.contains(containerCreateWeight), "containerCreate weight must be in range [0.0, 100.0] [%s]", containerCreateWeight); checkArgument(PERCENTAGE.contains(writeMultipartWeight), "writeMultipart weight must be in range [0.0, 100.0] [%s]", writeMultipartWeight); final double sum = writeWeight + readWeight + deleteWeight + metadataWeight + overwriteWeight + listWeight + containerListWeight + containerCreateWeight + writeMultipartWeight; checkArgument(DoubleMath.fuzzyEquals(sum, 100.0, ERR), "sum of weights must be 100.0 [%s]", sum); final RandomSupplier.Builder<Supplier<Request>> wrc = Suppliers.random(); if (writeWeight > 0.0) { wrc.withChoice(write, writeWeight); } if (overwriteWeight > 0.0) { wrc.withChoice(overwrite, overwriteWeight); } if (readWeight > 0.0) { wrc.withChoice(read, readWeight); } if (metadataWeight > 0.0) { wrc.withChoice(metadata, metadataWeight); } if (deleteWeight > 0.0) { wrc.withChoice(delete, deleteWeight); } if (listWeight > 0.0) { wrc.withChoice(list, listWeight); } if (containerListWeight > 0.0) { wrc.withChoice(containerList, containerListWeight); } if (containerCreateWeight > 0.0) { wrc.withChoice(containerCreate, containerCreateWeight); } if (writeMultipartWeight > 0.0) { wrc.withChoice(writeMultipart, writeMultipartWeight); } this.requestSupplier = wrc.build(); }
From source file:com.opengamma.strata.basics.currency.Money.java
/** * Converts this amount to an equivalent amount the specified currency. * <p>//w w w .j a v a 2s.c o m * The result will be expressed in terms of the given currency, converting * using the specified FX rate. * <p> * For example, if this represents 'GBP 100' and this method is called with * arguments {@code (USD, 1.6)} then the result will be 'USD 160'. * * @param resultCurrency the currency of the result * @param fxRate the FX rate from this currency to the result currency * @return the converted instance, which should be expressed in the specified currency * @throws IllegalArgumentException if the FX is not 1 when no conversion is required */ public Money convertedTo(Currency resultCurrency, BigDecimal fxRate) { if (currency.equals(resultCurrency)) { if (DoubleMath.fuzzyEquals(fxRate.doubleValue(), 1d, 1e-8)) { return this; } throw new IllegalArgumentException("FX rate must be 1 when no conversion required"); } return Money.of(resultCurrency, amount.multiply(fxRate)); }
From source file:org.apache.brooklyn.enricher.stock.PercentageEnricher.java
@Override public void onEvent(SensorEvent<Number> event) { Number current = producer.sensors().get(sourceCurrentSensor); if (current == null) { LOG.trace("Can't calculate percentage value for entity {} as current from producer {} is null", entity, producer);//from w w w .j av a 2s . co m return; } Number total = producer.sensors().get(sourceTotalSensor); if (total == null) { LOG.trace("Can't calculate percentage value for entity {} as total from producer {} is null", entity, producer); return; } Double currentDouble = current.doubleValue(); Double totalDouble = total.doubleValue(); if (DoubleMath.fuzzyEquals(totalDouble, 0d, EPSILON)) { LOG.trace("Can't calculate percentage value for entity {} as total from producer {} is zero", entity, producer); return; } if (currentDouble < 0d || totalDouble < 0d) { LOG.trace( "Can't calculate percentage value for entity {} as current ({}) or total ({}) from producer {} is negative", new Object[] { entity, currentDouble, totalDouble, producer }); return; } Double result = currentDouble / totalDouble; emit(targetSensor, result); }
From source file:com.analog.lyric.dimple.model.domains.DiscreteDomain.java
private static <T> TypedDiscreteDomain<T> create(T firstElt, int offset, Object[] moreElements) { int size = moreElements.length; Class<?> eltClass = firstElt.getClass(); if (eltClass.isEnum() && ((Enum<?>) firstElt).ordinal() == 0) { boolean useEnumDomain = true; for (int i = offset; i < size; ++i) { Object elt = moreElements[i]; if (elt.getClass() != eltClass || ((Enum<?>) elt).ordinal() != (i + 1)) { useEnumDomain = false;/*from w w w. j av a 2s .c o m*/ break; } } if (useEnumDomain) { @SuppressWarnings({ "unchecked", "rawtypes" }) TypedDiscreteDomain<T> domain = intern(new EnumDomain(eltClass)); return domain; } } else if (Integer.class.isAssignableFrom(eltClass)) { // We could eliminate the instanceof checks if the component type of the 'elements' // array is Integer... if (size > offset && moreElements[offset] instanceof Integer) { int first = ((Integer) firstElt).intValue(); int prev = ((Integer) moreElements[offset]).intValue(); int interval = prev - first; if (interval > 0) { boolean useIntRangeDomain = true; for (int i = offset + 1; i < size; ++i) { Object element = moreElements[i]; if (element instanceof Integer) { int next = prev + interval; if (next == ((Integer) element).intValue()) { prev = next; continue; } } useIntRangeDomain = false; break; } if (useIntRangeDomain) { @SuppressWarnings("unchecked") TypedDiscreteDomain<T> domain = (TypedDiscreteDomain<T>) range(first, prev, interval); return domain; } } } } else if (Double.class.isAssignableFrom(eltClass)) { if (size > offset && moreElements[offset] instanceof Double) { double first = ((Double) firstElt).doubleValue(); double prev = ((Double) moreElements[offset]).doubleValue(); double interval = prev - first; if (interval > 0.0) { double tolerance = DoubleRangeDomain.defaultToleranceForInterval(interval); boolean useDoubleRangeDomain = true; for (int i = 1 + offset; i < size; ++i) { Object element = moreElements[i]; if (element instanceof Double) { double next = prev + interval; if (DoubleMath.fuzzyEquals(next, (Double) element, tolerance)) { prev = next; continue; } } useDoubleRangeDomain = false; break; } if (useDoubleRangeDomain) { @SuppressWarnings("unchecked") TypedDiscreteDomain<T> domain = (TypedDiscreteDomain<T>) range(first, prev, interval, tolerance); return domain; } } } } return intern(new ArrayDiscreteDomain<T>(firstElt, offset, moreElements)); }
From source file:com.opengamma.strata.pricer.impl.option.BlackBarrierPriceFormulaRepository.java
/** * Computes the price and derivatives of a barrier option. * /*w w w .j ava 2s .c o m*/ * The derivatives are [0] spot, [1] strike, [2] rate, [3] cost-of-carry, [4] volatility, [5] timeToExpiry, [6] spot twice * * @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 and derivatives */ public ValueDerivatives priceAdjoint(double spot, double strike, double timeToExpiry, double costOfCarry, double rate, double lognormalVol, boolean isCall, SimpleConstantContinuousBarrier barrier) { ArgChecker.notNull(barrier, "barrier"); double[] derivatives = new double[7]; 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 lognormalVolSq = lognormalVol * lognormalVol; double lognormalVolT = lognormalVol * Math.sqrt(timeToExpiry); if (DoubleMath.fuzzyEquals(Math.min(timeToExpiry, lognormalVolSq), 0d, SMALL)) { if (isKnockIn) { return ValueDerivatives.of(0d, DoubleArray.filled(7)); } double dscFwd = df1 * spot; double dscStr = df2 * strike; double price = 0d; if (isCall) { if (dscFwd >= dscStr) { price = dscFwd - dscStr; derivatives[0] = df1; derivatives[1] = -df2; derivatives[2] = -timeToExpiry * price; derivatives[3] = timeToExpiry * dscFwd; derivatives[5] = (costOfCarry - rate) * dscFwd + rate * dscStr; } } else { if (dscStr >= dscFwd) { price = dscStr - dscFwd; derivatives[0] = -df1; derivatives[1] = df2; derivatives[2] = -timeToExpiry * price; derivatives[3] = -timeToExpiry * dscFwd; derivatives[5] = -rate * dscStr - (costOfCarry - rate) * dscFwd; } } return ValueDerivatives.of(price, DoubleArray.ofUnsafe(derivatives)); } double mu = (costOfCarry - 0.5 * lognormalVolSq) / lognormalVolSq; double m1 = lognormalVolT * (1 + mu); double x1 = Math.log(spot / strike) / lognormalVolT + m1; double x2 = Math.log(spot / h) / lognormalVolT + m1; double y1 = Math.log(h * h / spot / strike) / lognormalVolT + m1; double y2 = Math.log(h / spot) / lognormalVolT + m1; double[] aDerivFirst = new double[6]; double[][] aDerivSecond = new double[2][2]; double xA = getAAdjoint(spot, strike, df1, df2, x1, lognormalVolT, phi, aDerivFirst, aDerivSecond); double[] bDerivFirst = new double[6]; double[][] bDerivSecond = new double[2][2]; double xB = getAAdjoint(spot, strike, df1, df2, x2, lognormalVolT, phi, bDerivFirst, bDerivSecond); double[] cDerivFirst = new double[7]; double[][] cDerivSecond = new double[2][2]; double xC = getCAdjoint(spot, strike, df1, df2, y1, lognormalVolT, h, mu, phi, eta, cDerivFirst, cDerivSecond); double[] dDerivFirst = new double[7]; double[][] dDerivSecond = new double[2][2]; double xD = getCAdjoint(spot, strike, df1, df2, y2, lognormalVolT, h, mu, phi, eta, dDerivFirst, dDerivSecond); double xDBar = 0d; double xCBar = 0d; double xBBar = 0d; double xABar = 0d; double price; if (isKnockIn) { // IN start if (isDown) { // DOWN start if (isCall) { // Call start if (strike > h) { xCBar = 1d; price = xC; } else { xABar = 1d; xBBar = -1d; xDBar = 1d; price = xA - xB + xD; } } else { // Put start if (strike > h) { xBBar = 1d; xCBar = -1d; xDBar = 1d; price = xB - xC + xD; } else { xABar = 1d; price = xA; } } // DOWN end } else { // UP start if (isCall) { if (strike > h) { xABar = 1d; price = xA; } else { xBBar = 1d; xCBar = -1d; xDBar = 1d; price = xB - xC + xD; } } else { if (strike > h) { xABar = 1d; xBBar = -1d; xDBar = 1d; price = xA - xB + xD; } else { xCBar = 1d; price = xC; } } // UP end } // IN end } else { // OUT start if (isDown) { // DOWN start if (isCall) { // CALL start if (strike > h) { xABar = 1d; xCBar = -1d; price = xA - xC; } else { xBBar = 1d; xDBar = -1d; price = xB - xD; } } else { // PUT start if (strike > h) { xABar = 1d; xBBar = -1d; xCBar = 1d; xDBar = -1d; price = xA - xB + xC - xD; } else { price = 0d; } // PUT end } // DOWN end } else { // UP start if (isCall) { if (strike > h) { price = 0d; } else { xABar = 1d; xBBar = -1d; xCBar = 1d; xDBar = -1d; price = xA - xB + xC - xD; } } else { if (strike > h) { xBBar = 1d; xDBar = -1d; price = xB - xD; } else { xABar = 1d; xCBar = -1d; price = xA - xC; } // PUT end } // UP end } // OUT end } double dxyds = 1d / spot / lognormalVolT; double x1Bar = aDerivFirst[4] * xABar; double x2Bar = bDerivFirst[4] * xBBar; double y1Bar = cDerivFirst[4] * xCBar; double y2Bar = dDerivFirst[4] * xDBar; double m1Bar = x1Bar + x2Bar + y1Bar + y2Bar; double muBar = cDerivFirst[6] * xCBar + dDerivFirst[6] * xDBar + lognormalVolT * m1Bar; double lognormalVolTBar = aDerivFirst[5] * xABar + bDerivFirst[5] * xBBar + cDerivFirst[5] * xCBar + dDerivFirst[5] * xDBar - Math.log(h / spot) / (lognormalVolT * lognormalVolT) * y2Bar - Math.log(h * h / spot / strike) / (lognormalVolT * lognormalVolT) * y1Bar - Math.log(spot / h) / (lognormalVolT * lognormalVolT) * x2Bar - Math.log(spot / strike) / (lognormalVolT * lognormalVolT) * x1Bar + (1d + mu) * m1Bar; double lognormalVolSqBar = -costOfCarry / (lognormalVolSq * lognormalVolSq) * muBar; double df2Bar = aDerivFirst[3] * xABar + bDerivFirst[3] * xBBar + cDerivFirst[3] * xCBar + dDerivFirst[3] * xDBar; double df1Bar = aDerivFirst[2] * xABar + bDerivFirst[2] * xBBar + cDerivFirst[2] * xCBar + dDerivFirst[2] * xDBar; derivatives[0] = aDerivFirst[0] * xABar + bDerivFirst[0] * xBBar + cDerivFirst[0] * xCBar + dDerivFirst[0] * xDBar + x1Bar * dxyds + x2Bar * dxyds - y1Bar * dxyds - y2Bar * dxyds; derivatives[1] = aDerivFirst[1] * xABar + bDerivFirst[1] * xBBar + cDerivFirst[1] * xCBar + dDerivFirst[1] * xDBar - (x1Bar + y1Bar) / strike / lognormalVolT; derivatives[2] = -timeToExpiry * (df1 * df1Bar + df2 * df2Bar); derivatives[3] = timeToExpiry * df1 * df1Bar + muBar / lognormalVolSq; derivatives[4] = 2d * lognormalVol * lognormalVolSqBar + Math.sqrt(timeToExpiry) * lognormalVolTBar; derivatives[5] = (costOfCarry - rate) * df1 * df1Bar - rate * df2 * df2Bar + lognormalVolTBar * lognormalVolT * 0.5 / timeToExpiry; derivatives[6] = aDerivSecond[0][0] * xABar + bDerivSecond[0][0] * xBBar + cDerivSecond[0][0] * xCBar + dDerivSecond[0][0] * xDBar + 2d * xABar * aDerivSecond[0][1] * dxyds + 2d * xBBar * bDerivSecond[0][1] * dxyds - 2d * xCBar * cDerivSecond[0][1] * dxyds - 2d * xDBar * dDerivSecond[0][1] * dxyds + xABar * aDerivSecond[1][1] * dxyds * dxyds + xBBar * bDerivSecond[1][1] * dxyds * dxyds + xCBar * cDerivSecond[1][1] * dxyds * dxyds + xDBar * dDerivSecond[1][1] * dxyds * dxyds - x1Bar * dxyds / spot - x2Bar * dxyds / spot + y1Bar * dxyds / spot + y2Bar * dxyds / spot; return ValueDerivatives.of(price, DoubleArray.ofUnsafe(derivatives)); }
From source file:com.intuit.wasabi.analytics.impl.AnalysisToolsImpl.java
/** * {@inheritDoc}/*w w w .jav a2 s .co m*/ */ @Override public void generateBucketComparison(Map<Bucket.Label, BucketStatistics> buckets, BinomialMetrics.BinomialMetric metric, double effectSize, Parameters.Mode mode) { //loop over the set of buckets twice to get the two buckets to compare for (BucketStatistics bucket : buckets.values()) { for (BucketStatistics otherBucket : buckets.values()) { //don't compare a bucket to itself if (bucket != otherBucket) { long bucketImpressions = bucket.getImpressionCounts().getUniqueUserCount(); long otherBucketImpressions = otherBucket.getImpressionCounts().getUniqueUserCount(); //calculate the joint action comparison long bucketUniqueCounts = bucket.getJointActionCounts().getUniqueUserCount(); long otherBucketUniqueCounts = otherBucket.getJointActionCounts().getUniqueUserCount(); Estimate rateDifference; try { rateDifference = metric.estimateRateDifference(bucketImpressions, bucketUniqueCounts, otherBucketImpressions, otherBucketUniqueCounts); } catch (IllegalArgumentException iae) { LOGGER.warn( "BinomialMetric.estimateRateDifference called with invalid arguments by AnalyticsService.generateBucketComparisons: ", iae); rateDifference = new Estimate(NaN, NaN, NaN); } Double fractionData; fractionData = computeFractionData(metric, effectSize, mode, bucketImpressions, otherBucketImpressions, bucketUniqueCounts, otherBucketUniqueCounts); DistinguishableEffectSize effects; try { effects = metric.distinguishableEffectSizes(bucketImpressions, bucketUniqueCounts, otherBucketImpressions, otherBucketUniqueCounts); } catch (IllegalArgumentException iae) { LOGGER.warn( "BinomialMetric.distinguishableEffectSizes called with invalid arguments by AnalyticsService.generateBucketComparisons: ", iae); effects = new DistinguishableEffectSize(NaN, NaN); } ComparisonStatistics jointComparison = new ComparisonStatistics.Builder() .withActionRateDifference(rateDifference).withSmallestDistinguishableEffectSize(effects) .withFractionDataCollected(fractionData).build(); jointComparison.setSufficientData(DoubleMath.fuzzyEquals(fractionData, 1.0, Math.ulp(1.0))); computeClearComparisonWinner(bucket, otherBucket, rateDifference, jointComparison); //loop over shared actions within the buckets to calculate comparisons Map<Event.Name, ActionComparisonStatistics> actionsComparisons = new HashMap<>(); Map<Event.Name, ActionCounts> actionCounts = bucket.getActionCounts(); Map<Event.Name, ActionCounts> otherActionCounts = otherBucket.getActionCounts(); Set<Event.Name> sharedNames = new HashSet<>(actionCounts.keySet()); sharedNames.retainAll(otherActionCounts.keySet()); for (Event.Name actionName : sharedNames) { ActionCounts action = actionCounts.get(actionName); ActionCounts otherAction = otherActionCounts.get(actionName); bucketUniqueCounts = action.getUniqueUserCount(); otherBucketUniqueCounts = otherAction.getUniqueUserCount(); try { rateDifference = metric.estimateRateDifference(bucketImpressions, bucketUniqueCounts, otherBucketImpressions, otherBucketUniqueCounts); } catch (IllegalArgumentException iae) { LOGGER.warn( "BinomialMetric.estimateRateDifference called with invalid arguments by AnalyticsService.generateBucketComparisons: ", iae); rateDifference = new Estimate(NaN, NaN, NaN); } fractionData = computeFractionData(metric, effectSize, mode, bucketImpressions, otherBucketImpressions, bucketUniqueCounts, otherBucketUniqueCounts); try { effects = metric.distinguishableEffectSizes(bucketImpressions, bucketUniqueCounts, otherBucketImpressions, otherBucketUniqueCounts); } catch (IllegalArgumentException iae) { LOGGER.warn( "BinomialMetric.distinguishableEffectSizes called with invalid arguments by AnalyticsService.generateBucketComparisons: ", iae); effects = new DistinguishableEffectSize(NaN, NaN); } ActionComparisonStatistics actionComparison = new ActionComparisonStatistics.Builder() .withActionName(actionName).withActionRateDifference(rateDifference) .withSmallestDistinguishableEffectSize(effects) .withFractionDataCollected(fractionData).build(); actionComparison .setSufficientData(DoubleMath.fuzzyEquals(fractionData, 1.0, Math.ulp(1.0))); computeClearComparisonWinner(bucket, otherBucket, rateDifference, actionComparison); actionsComparisons.put(actionName, actionComparison); } Bucket.Label otherBucketLabel = otherBucket.getLabel(); BucketComparison comparison = new BucketComparison.Builder().withOtherLabel(otherBucketLabel) .withJointActionComparison(jointComparison).withActionComparisons(actionsComparisons) .build(); bucket.addToBucketComparisons(otherBucketLabel, comparison); } } } }
From source file:com.analog.lyric.dimple.solvers.core.parameterizedMessages.NormalParameters.java
/** * Adds natural parameters from another {@link NormalParameters} object * <p>//from w w w . jav a2 s . co m * @throws InvalidDistributionException if both objects have infinite {@linkplain #getPrecision() precision} * with different {@linkplain #getMean() means}. * @since 0.08 */ public void addFrom(NormalParameters other) { // That natural parameters are: mean*precision and precision // // Special cases: // - both precisions infinite: average means if close enough, otherwise NaN // - one precision infinite: use corresponding mean // - one precision is zero: use other mean final double otherPrecision = other._precision; if (otherPrecision == 0.0) { // Other message doesn't add any information. return; } final double precision = _precision; if (precision == 0.0) { // This message doesn't contribute any information _mean = other._mean; _precision = otherPrecision; return; } if (precision == Double.POSITIVE_INFINITY) { if (otherPrecision == Double.POSITIVE_INFINITY) { if (!DoubleMath.fuzzyEquals(_mean, other._mean, Math.abs(_mean) / 1e12)) { throw new InvalidDistributionException( "Cannot combine NormalParameters with infinite precision and different means (%g and %g", _mean, other._mean); } } else { // Infinite precision overrides other message } return; } if (otherPrecision == Double.POSITIVE_INFINITY) { // Infinite precision in other message overrides this one _mean = other._mean; _precision = otherPrecision; return; } // Regular case _precision += otherPrecision; _mean = (_mean * precision + other._mean * otherPrecision) / _precision; }
From source file:nova.core.util.transform.Quaternion.java
@Override public boolean equals(Object obj) { if (obj instanceof Quaternion) { Quaternion other = ((Quaternion) obj); return DoubleMath.fuzzyEquals(this.x, other.x, 0.000001) && DoubleMath.fuzzyEquals(this.y, other.y, 0.000001) && DoubleMath.fuzzyEquals(this.z, other.z, 0.000001) && DoubleMath.fuzzyEquals(this.w, other.w, 0.000001); }/*from w w w . j a v a2 s. c om*/ return this == obj; }
From source file:com.opengamma.strata.pricer.impl.volatility.smile.function.SabrHaganVolatilityFunctionProvider.java
/** * Computes the implied volatility in the SABR model and its derivatives. * <p>/*from w w w . j a va 2s. c o m*/ * The derivatives are stored in an array with: * <ul> * <li>[0] derivative with respect to the forward * <li>[1] derivative with respect to the strike * <li>[2] derivative with respect to the alpha * <li>[3] derivative with respect to the beta * <li>[4] derivative with respect to the rho * <li>[5] derivative with respect to the nu * </ul> * * @param forward the forward value of the underlying * @param strike the strike value of the option * @param timeToExpiry the time to expiry of the option * @param data the SABR data * @return the volatility and associated derivatives */ @Override public ValueDerivatives getVolatilityAdjoint(double forward, double strike, double timeToExpiry, SabrFormulaData data) { ArgChecker.isTrue(forward > 0.0, "forward must be greater than zero"); ArgChecker.isTrue(strike >= 0.0, "strike must be greater than zero"); ArgChecker.isTrue(timeToExpiry >= 0.0, "timeToExpiry must be greater than zero"); double alpha = data.getAlpha(); double cutoff = forward * CUTOFF_MONEYNESS; double k = strike; if (k < cutoff) { Logger s_logger = LoggerFactory.getLogger(SabrHaganVolatilityFunctionProvider.class); s_logger.info("Given strike of {} is less than cutoff at {}, therefore the strike is taken as {}", new Object[] { k, cutoff, cutoff }); k = cutoff; } double beta = data.getBeta(); double betaStar = 1 - beta; double rho = data.getRho(); double nu = data.getNu(); double rhoStar = 1.0 - rho; if (alpha == 0.0) { double alphaBar; if (DoubleMath.fuzzyEquals(forward, k, ATM_EPS)) { //TODO should this is relative alphaBar = (1 + (2 - 3 * rho * rho) * nu * nu / 24 * timeToExpiry) / Math.pow(forward, betaStar); } else { //for non-atm options the alpha sensitivity at alpha = 0 is infinite. Returning this will most likely break calibrations, // so we return an arbitrary large number alphaBar = 1e7; } return ValueDerivatives.of(0d, DoubleArray.of(0, 0, alphaBar, 0, 0, 0)); } // Implementation note: Forward sweep. double sfK = Math.pow(forward * k, betaStar / 2); double lnrfK = Math.log(forward / k); double z = nu / alpha * sfK * lnrfK; double rzxz; double xz = 0; if (DoubleMath.fuzzyEquals(z, 0.0, SMALL_Z)) { rzxz = 1.0 - 0.5 * z * rho; //small z expansion to z^2 terms } else { if (DoubleMath.fuzzyEquals(rhoStar, 0.0, RHO_EPS)) { if (z >= 1.0) { if (rhoStar == 0.0) { rzxz = 0.0; xz = Double.POSITIVE_INFINITY; } else { xz = (Math.log(2 * (z - 1)) - Math.log(rhoStar)); rzxz = z / xz; } } else { xz = -Math.log(1 - z) - 0.5 * Math.pow(z / (z - 1.0), 2) * rhoStar; rzxz = z / xz; } } else { double arg; if (z < LARGE_NEG_Z) { arg = (rho * rho - 1) / 2 / z; //get rounding errors due to fine balanced cancellation for very large negative z } else if (z > LARGE_POS_Z) { arg = 2 * (z - rho); } else { arg = (Math.sqrt(1 - 2 * rho * z + z * z) + z - rho); } if (arg <= 0.0) { //Mathematically this cannot be less than zero, but you know what computers are like. rzxz = 0.0; } else { xz = Math.log(arg / (1 - rho)); rzxz = z / xz; } } } double sf1 = sfK * (1 + betaStar * betaStar / 24 * (lnrfK * lnrfK) + Math.pow(betaStar, 4) / 1920 * Math.pow(lnrfK, 4)); double sf2 = (1 + (Math.pow(betaStar * alpha / sfK, 2) / 24 + (rho * beta * nu * alpha) / (4 * sfK) + (2 - 3 * rho * rho) * nu * nu / 24) * timeToExpiry); double volatility = alpha / sf1 * rzxz * sf2; // Implementation note: Backward sweep. double vBar = 1; double sf2Bar = alpha / sf1 * rzxz * vBar; double sf1Bar = -alpha / (sf1 * sf1) * rzxz * sf2 * vBar; double rzxzBar = alpha / sf1 * sf2 * vBar; double zBar; double xzBar = 0.0; if (DoubleMath.fuzzyEquals(z, 0.0, SMALL_Z)) { zBar = -rho / 2 * rzxzBar; } else { if (DoubleMath.fuzzyEquals(rhoStar, 0.0, RHO_EPS)) { if (z >= 1.0) { if (z == 1.0) { zBar = 0.0; } else { double chiDz = 1 / (z - 1); xzBar = -rzxzBar * z / (xz * xz); zBar = volatility / z + chiDz * xzBar; } } else { zBar = -1.0 / Math.log(1 - z) * (1 + z / Math.log(1 - z) / (1 - z)) * rzxzBar; xzBar = -z / (xz * xz) * rzxzBar; } } else { if (z < LARGE_NEG_Z) { zBar = 1 / xz * rzxzBar + xzBar / (xz * xz) * rzxzBar; } else if (z > LARGE_POS_Z) { zBar = 1 / xz * rzxzBar - xzBar / (xz * xz) * rzxzBar; } else { xzBar = -z / (xz * xz) * rzxzBar; zBar = 1 / xz * rzxzBar + 1 / ((Math.sqrt(1 - 2 * rho * z + z * z) + z - rho)) * (0.5 * Math.pow(1 - 2 * rho * z + z * z, -0.5) * (-2 * rho + 2 * z) + 1) * xzBar; } } } double lnrfKBar = sfK * (betaStar * betaStar / 12 * lnrfK + Math.pow(betaStar, 4) / 1920 * 4 * Math.pow(lnrfK, 3)) * sf1Bar + nu / alpha * sfK * zBar; double sfKBar = nu / alpha * lnrfK * zBar + sf1 / sfK * sf1Bar - (Math.pow(betaStar * alpha, 2) / Math.pow(sfK, 3) / 12 + (rho * beta * nu * alpha) / 4 / (sfK * sfK)) * timeToExpiry * sf2Bar; double strikeBar = -1 / k * lnrfKBar + betaStar * sfK / (2 * k) * sfKBar; double forwardBar = 1 / forward * lnrfKBar + betaStar * sfK / (2 * forward) * sfKBar; double nuBar = 1 / alpha * sfK * lnrfK * zBar + ((rho * beta * alpha) / (4 * sfK) + (2 - 3 * rho * rho) * nu / 12) * timeToExpiry * sf2Bar; double rhoBar; if (Math.abs(forward - k) < ATM_EPS) { rhoBar = -z / 2 * rzxzBar; } else { if (DoubleMath.fuzzyEquals(rhoStar, 0.0, RHO_EPS)) { if (z >= 1) { if (rhoStar == 0.0) { rhoBar = Double.NEGATIVE_INFINITY; //the derivative at rho = 1 is infinite - this sets it to some arbitrary large number } else { rhoBar = xzBar * (1.0 / rhoStar + (0.5 - z) / (z - 1.0) / (z - 1.0)); } } else { rhoBar = (0.5 * Math.pow(z / (1 - z), 2) + 0.25 * (z - 4.0) * Math.pow(z / (1.0 - z), 3) / (1.0 - z) * rhoStar) * xzBar; } } else { rhoBar = (1 / (Math.sqrt(1 - 2 * rho * z + z * z) + z - rho) * (-Math.pow(1 - 2 * rho * z + z * z, -0.5) * z - 1) + 1 / rhoStar) * xzBar; } } rhoBar += ((beta * nu * alpha) / (4 * sfK) - rho * nu * nu / 4) * timeToExpiry * sf2Bar; double alphaBar = -nu / (alpha * alpha) * sfK * lnrfK * zBar + ((betaStar * alpha / sfK) * (betaStar / sfK) / 12 + (rho * beta * nu) / (4 * sfK)) * timeToExpiry * sf2Bar + 1 / sf1 * rzxz * sf2 * vBar; double betaBar = -0.5 * Math.log(forward * k) * sfK * sfKBar - sfK * (betaStar / 12 * (lnrfK * lnrfK) + Math.pow(betaStar, 3) / 480 * Math.pow(lnrfK, 4)) * sf1Bar + (-betaStar * alpha * alpha / sfK / sfK / 12 + rho * nu * alpha / 4 / sfK) * timeToExpiry * sf2Bar; return ValueDerivatives.of(volatility, DoubleArray.of(forwardBar, strikeBar, alphaBar, betaBar, rhoBar, nuBar)); }
From source file:org.eclipse.tracecompass.internal.pcap.core.stream.PacketStream.java
/** * Get the the average byte per second from A to B. * * @return the average byte per second from A to B. *//*from ww w .ja va 2 s .co m*/ public synchronized double getBPSAtoB() { if (DoubleMath.fuzzyEquals(getDuration(), 0, DELTA)) { return 0; } return fNbBytesAtoB / getDuration(); }