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.hawkular.metrics.core.service.AvailabilityBucketPointMatcher.java
@Override protected boolean matchesSafely(AvailabilityBucketPoint item) { return item.getStart() == expected.getStart() && item.getEnd() == expected.getEnd() && item.getNotUpCount() == expected.getNotUpCount() && item.getDurationMap().equals(expected.getDurationMap()) && item.getLastNotUptime() == expected.getLastNotUptime() && DoubleMath.fuzzyEquals(item.getUptimeRatio(), expected.getUptimeRatio(), 0.001); }
From source file:org.hawkular.metrics.core.impl.AvailabilityBucketPointMatcher.java
@Override protected boolean matchesSafely(AvailabilityBucketPoint item) { return item.getStart() == expected.getStart() && item.getEnd() == expected.getEnd() && item.getDowntimeCount() == expected.getDowntimeCount() && item.getDowntimeDuration() == expected.getDowntimeDuration() && item.getLastDowntime() == expected.getLastDowntime() && DoubleMath.fuzzyEquals(item.getUptimeRatio(), expected.getUptimeRatio(), 0.001); }
From source file:org.hawkular.metrics.core.impl.AvailabilityBucketDataPointMatcher.java
@Override protected boolean matchesSafely(AvailabilityBucketDataPoint item) { return item.getStart() == expected.getStart() && item.getEnd() == expected.getEnd() && item.getDowntimeCount() == expected.getDowntimeCount() && item.getDowntimeDuration() == expected.getDowntimeDuration() && item.getLastDowntime() == expected.getLastDowntime() && DoubleMath.fuzzyEquals(item.getUptimeRatio(), expected.getUptimeRatio(), 0.001); }
From source file:com.opengamma.strata.math.impl.rootfinding.LaguerrePolynomialRealRootFinder.java
/** * {@inheritDoc}//from w ww. j a va2s .co m * @throws MathException If there are no real roots; if the Commons method could not evaluate the function; if the Commons method could not converge. */ @Override public Double[] getRoots(RealPolynomialFunction1D function) { ArgChecker.notNull(function, "function"); try { Complex[] roots = ROOT_FINDER.solveAllComplex(function.getCoefficients(), 0); List<Double> realRoots = new ArrayList<>(); for (Complex c : roots) { if (DoubleMath.fuzzyEquals(c.getImaginary(), 0d, EPS)) { realRoots.add(c.getReal()); } } if (realRoots.isEmpty()) { throw new MathException("Could not find any real roots"); } return realRoots.toArray(new Double[realRoots.size()]); } catch (TooManyEvaluationsException e) { throw new MathException(e); } }
From source file:com.ibm.og.util.Distributions.java
/** * Creates a normal distribution with a rangge of [average - 3*spread, average + 3*spread]. * //from ww w . j av a 2 s . co m * @param average the center of this distribution * @param spread distance of one standard deviation * @return a normal distribution instance * @throws IllegalArgumentException if average or spread are negative, or if average - 3*spread is * negative */ public static Distribution normal(final double average, final double spread) { 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("NormalDistribution [average=%s, spread=%s]", average, spread); return new RealDistributionAdapter(new NormalDistribution(average, spread), s); }
From source file:com.ibm.og.scheduling.ConcurrentRequestScheduler.java
/** * Constructs an instance with the provided concurrency * /*from w w w . j a v a2s .c o m*/ * @param concurrentRequests the number of concurrent requests allowed * @throws IllegalArgumentException if concurrentRequests is negative or zero */ public ConcurrentRequestScheduler(final int concurrentRequests, final double rampup, final TimeUnit rampupUnit) { checkArgument(concurrentRequests > 0, "concurrentRequests must be > 0"); checkArgument(rampup >= 0.0, "rampup must be >= 0.0 [%s]", rampup); checkNotNull(rampupUnit); this.concurrentRequests = concurrentRequests; this.rampup = rampup; this.rampupUnit = rampupUnit; this.started = new CountDownLatch(1); if (DoubleMath.fuzzyEquals(rampup, 0.0, Math.pow(0.1, 6))) { this.permits = new Semaphore(concurrentRequests); } else { this.permits = new Semaphore(0); final Thread rampupThread = new Thread(new Runnable() { @Override public void run() { final double rampSeconds = (rampup * rampupUnit.toNanos(1)) / TimeUnit.SECONDS.toNanos(1); _logger.debug("Ramp seconds [{}]", rampSeconds); final RateLimiter ramp = RateLimiter.create(concurrentRequests / rampSeconds); _logger.debug("Ramp rate [{}]", ramp.getRate()); _logger.debug("Awaiting start latch"); Uninterruptibles.awaitUninterruptibly(ConcurrentRequestScheduler.this.started); _logger.info("Starting ramp"); for (int i = 0; i < concurrentRequests; i++) { _logger.debug("Acquiring RateLimiter permit"); ramp.acquire(); _logger.debug("Releasing semaphore permit"); ConcurrentRequestScheduler.this.permits.release(); } _logger.info("Finished ramp"); } }, "concurrent-scheduler-ramp"); rampupThread.setDaemon(true); rampupThread.start(); _logger.debug("Starting permits [{}]", this.permits.availablePermits()); } }
From source file:com.opengamma.strata.math.impl.rootfinding.CubicRootFinder.java
/** * {@inheritDoc}//from w ww .j a v a2s .c o m * @throws IllegalArgumentException If the function is not cubic */ @Override public ComplexNumber[] getRoots(RealPolynomialFunction1D function) { ArgChecker.notNull(function, "function"); double[] coefficients = function.getCoefficients(); ArgChecker.isTrue(coefficients.length == 4, "Function is not a cubic"); double divisor = coefficients[3]; double a = coefficients[2] / divisor; double b = coefficients[1] / divisor; double c = coefficients[0] / divisor; double aSq = a * a; double q = (aSq - 3 * b) / 9; double r = (2 * a * aSq - 9 * a * b + 27 * c) / 54; double rSq = r * r; double qCb = q * q * q; double constant = a / 3; if (rSq < qCb) { double mult = -2 * Math.sqrt(q); double theta = Math.acos(r / Math.sqrt(qCb)); return new ComplexNumber[] { new ComplexNumber(mult * Math.cos(theta / 3) - constant, 0), new ComplexNumber(mult * Math.cos((theta + TWO_PI) / 3) - constant, 0), new ComplexNumber(mult * Math.cos((theta - TWO_PI) / 3) - constant, 0) }; } double s = -Math.signum(r) * Math.cbrt(Math.abs(r) + Math.sqrt(rSq - qCb)); double t = DoubleMath.fuzzyEquals(s, 0d, 1e-16) ? 0 : q / s; double sum = s + t; double real = -0.5 * sum - constant; double imaginary = Math.sqrt(3) * (s - t) / 2; return new ComplexNumber[] { new ComplexNumber(sum - constant, 0), new ComplexNumber(real, imaginary), new ComplexNumber(real, -imaginary) }; }
From source file:com.opengamma.strata.pricer.impl.option.NormalImpliedVolatilityFormula.java
/** * Computes the implied volatility from the option price in a normally distributed asset price world. * <p>/* w w w . ja v a 2 s . com*/ * If the volatility data is not zero, it is used as a starting point for the volatility search. * * @param data the model data * @param option the option * @param optionPrice the option price * @return the implied volatility */ public double impliedVolatility(NormalFunctionData data, EuropeanVanillaOption option, double optionPrice) { double numeraire = data.getNumeraire(); boolean isCall = option.isCall(); double f = data.getForward(); double k = option.getStrike(); double intrinsicPrice = numeraire * Math.max(0, (isCall ? 1 : -1) * (f - k)); ArgChecker.isTrue(optionPrice > intrinsicPrice || DoubleMath.fuzzyEquals(optionPrice, intrinsicPrice, 1e-6), "option price (" + optionPrice + ") less than intrinsic value (" + intrinsicPrice + ")"); if (Double.doubleToLongBits(optionPrice) == Double.doubleToLongBits(intrinsicPrice)) { return 0.0; } double sigma = (Math.abs(data.getNormalVolatility()) < 1e-10 ? 0.3 * f : data.getNormalVolatility()); NormalFunctionData newData = NormalFunctionData.of(f, numeraire, sigma); double maxChange = 0.5 * f; double[] priceDerivative = new double[3]; double price = NORMAL_PRICE_FUNCTION.getPriceAdjoint(option, newData, priceDerivative); double vega = priceDerivative[1]; double change = (price - optionPrice) / vega; double sign = Math.signum(change); change = sign * Math.min(maxChange, Math.abs(change)); if (change > 0 && change > sigma) { change = sigma; } int count = 0; while (Math.abs(change) > EPS) { sigma -= change; newData = NormalFunctionData.of(f, numeraire, sigma); price = NORMAL_PRICE_FUNCTION.getPriceAdjoint(option, newData, priceDerivative); vega = priceDerivative[1]; change = (price - optionPrice) / vega; sign = Math.signum(change); change = sign * Math.min(maxChange, Math.abs(change)); if (change > 0 && change > sigma) { change = sigma; } if (count++ > MAX_ITERATIONS) { BracketRoot bracketer = new BracketRoot(); BisectionSingleRootFinder rootFinder = new BisectionSingleRootFinder(EPS); Function1D<Double, Double> func = new Function1D<Double, Double>() { @SuppressWarnings({ "synthetic-access" }) @Override public Double evaluate(Double volatility) { NormalFunctionData myData = NormalFunctionData.of(data.getForward(), data.getNumeraire(), volatility); return NORMAL_PRICE_FUNCTION.getPriceFunction(option).evaluate(myData) - optionPrice; } }; double[] range = bracketer.getBracketedPoints(func, 0.0, 10.0); return rootFinder.getRoot(func, range[0], range[1]); } } return sigma; }
From source file:com.opengamma.strata.math.impl.statistics.distribution.GeneralizedExtremeValueDistribution.java
/** * //www. j av a 2 s. c o m * @param mu The location parameter * @param sigma The scale parameter, not negative or zero * @param ksi The shape parameter */ public GeneralizedExtremeValueDistribution(double mu, double sigma, double ksi) { ArgChecker.isTrue(sigma >= 0, "sigma must be >= 0"); _mu = mu; _sigma = sigma; _ksi = ksi; _ksiIsZero = DoubleMath.fuzzyEquals(ksi, 0d, 1e-13); }
From source file:com.ibm.og.scheduling.RequestRateScheduler.java
/** * Constructs an instance using the provided rate {@code count / unit } * //from w w w . jav a2 s . c o m * @param rate the numerator of the rate to configure * @param unit the denominator of the rate to configure * @param rampup the duration to ramp up to the stable request rate * @param rampupUnit the rampup duration unit */ public RequestRateScheduler(final double rate, final TimeUnit unit, final double rampup, final TimeUnit rampupUnit) { checkArgument(rate >= 0.0, "rate must be >= 0.0 [%s]", rate); this.rate = rate; this.unit = checkNotNull(unit); checkArgument(rampup >= 0.0, "rampup must be >= 0.0 [%s]", rampup); this.rampup = rampup; this.rampupUnit = checkNotNull(rampupUnit); this.permits = new AtomicReference<RateLimiter>(); // convert arbitrary rate unit to rate/second final double requestsPerSecond = requestsPerSecond(rate, unit); _logger.debug("Calculated requests per second [{}]", requestsPerSecond); if (DoubleMath.fuzzyEquals(rampup, 0.0, Math.pow(0.1, 6))) { final RateLimiter steady = RateLimiter.create(requestsPerSecond); this.permits.set(steady); } else { // the warmup Ratelimiter will not work if the permit request rate is slow enough to not being able to reach the // threshold from left. The permits are accumulated faster than the request rate here. // So the steady OPS will not be reached at all during warm up period. // Approximate the warm-up period with steady ratelimiter and set the ops for the steady rate limiter // based on the steady state ops, warm up duration. // calculate the ops based on the ramp duration and steady state ops final double slope = requestsPerSecond / (rampupUnit.toSeconds((long) rampup)); final int rampStepWidth = calculateStepWidth(rate, rampup, rampupUnit); this.permits.set(RateLimiter.create(slope * rampStepWidth * 1)); final Thread rampupThread = new Thread(new Runnable() { @Override public void run() { _logger.debug("Awaiting start latch"); Uninterruptibles.awaitUninterruptibly(RequestRateScheduler.this.started); _logger.info("Starting ramp"); double requestsPerSecondNow; RateLimiter rampRateLimiter; int rampStepNum = 1; int rampSteps = DoubleMath.roundToInt(((rampupUnit.toSeconds((long) rampup)) / rampStepWidth), RoundingMode.DOWN); _logger.info("ramp profile rampStepWidth {} NumRampSteps {} ", rampStepWidth, rampSteps); while (rampStepNum <= rampSteps) { Uninterruptibles.sleepUninterruptibly(rampStepWidth * 1000L, TimeUnit.MILLISECONDS); rampStepNum++; requestsPerSecondNow = slope * rampStepWidth * rampStepNum; _logger.debug("slope {} rampStep {} targetRequestPerSecond {} ", slope, rampStepNum, requestsPerSecondNow); rampRateLimiter = RateLimiter.create(requestsPerSecondNow); RequestRateScheduler.this.permits.set(rampRateLimiter); } final RateLimiter steady = RateLimiter.create(requestsPerSecond); RequestRateScheduler.this.permits.set(steady); _logger.info("Finished ramp"); } }, "rate-scheduler-ramp"); rampupThread.setDaemon(true); rampupThread.start(); } this.started = new CountDownLatch(1); }