com.google.common.math.DoubleMath Java Examples
The following examples show how to use
com.google.common.math.DoubleMath.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoordAxisHelper.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 6 votes |
private int findCoordElementDiscontiguousInterval(double[] target, boolean bounded) { // Check that the target is within range int n = axis.getNcoords(); double upperIndex = target[1] > target[0] ? target[1] : target[0]; double lowerIndex = upperIndex == target[1] ? target[0] : target[1]; if (lowerIndex < axis.getCoordEdge1(0)) return bounded ? 0 : -1; else if (upperIndex > axis.getCoordEdgeLast()) return bounded ? n - 1 : n; // see if we can find an exact match int index = -1; for (int i = 0; i < axis.getNcoords(); i++) { double edge1 = axis.getCoordEdge1(i); double edge2 = axis.getCoordEdge2(i); if (DoubleMath.fuzzyEquals(edge1, target[0], 1.0e-8) && DoubleMath.fuzzyEquals(edge2, target[1], 1.0e-8)) return i; } // ok, give up on exact match, try to find interval closest to midpoint of the target if (bounded) { index = findCoordElementDiscontiguousInterval(lowerIndex + (upperIndex - lowerIndex) / 2, bounded); } return index; }
Example #2
Source File: CubicRealRootFinder.java From Strata with Apache License 2.0 | 6 votes |
@Override public Double[] getRoots(RealPolynomialFunction1D function) { ArgChecker.notNull(function, "function"); double[] coefficients = function.getCoefficients(); if (coefficients.length != 4) { throw new IllegalArgumentException("Function is not a cubic"); } ComplexNumber[] result = ROOT_FINDER.getRoots(function); List<Double> reals = new ArrayList<>(); for (ComplexNumber c : result) { if (DoubleMath.fuzzyEquals(c.getImaginary(), 0d, 1e-16)) { reals.add(c.getReal()); } } ArgChecker.isTrue(reals.size() > 0, "Could not find any real roots"); return reals.toArray(EMPTY_ARRAY); }
Example #3
Source File: AggregationFunctionUtils.java From incubator-pinot with Apache License 2.0 | 6 votes |
public static String formatValue(Object value) { if (value instanceof Double) { double doubleValue = (double) value; // NOTE: String.format() is very expensive, so avoid it for whole numbers that can fit in Long. // We simply append ".00000" to long, in order to keep the existing behavior. if (doubleValue <= Long.MAX_VALUE && doubleValue >= Long.MIN_VALUE && DoubleMath .isMathematicalInteger(doubleValue)) { return (long) doubleValue + ".00000"; } else { return String.format(Locale.US, "%1.5f", doubleValue); } } else { return value.toString(); } }
Example #4
Source File: AllocationIdUtil.java From proctor with Apache License 2.0 | 6 votes |
private static boolean isUnbalancedRatioChange(final Allocation previous, final Allocation current) { Map<Integer, Double> previousRatios = getBucketRatios(previous.getRanges()); Map<Integer, Double> currentRatios = getBucketRatios(current.getRanges()); final Map<Integer, Double> before = filterEmptyRatios(previousRatios); final Map<Integer, Double> after = filterEmptyRatios(currentRatios); if (!before.keySet().equals(after.keySet())) { return true; } if (before.isEmpty()) { return false; } final int firstBucket = before.keySet().iterator().next(); final double firstRatio = after.get(firstBucket) / before.get(firstBucket); for (final int bucket : before.keySet()) { final double ratio = after.get(bucket) / before.get(bucket); if (!DoubleMath.fuzzyEquals(ratio, firstRatio, 1e-6)) { return true; } } return false; }
Example #5
Source File: TransformNullFunction.java From disthene-reader with MIT License | 6 votes |
@Override public List<TimeSeries> evaluate(TargetEvaluator evaluator) throws EvaluationException { List<TimeSeries> processedArguments = new ArrayList<>(); processedArguments.addAll(evaluator.eval((Target) arguments.get(0))); if (processedArguments.size() == 0) return new ArrayList<>(); if (!TimeSeriesUtils.checkAlignment(processedArguments)) { throw new TimeSeriesNotAlignedException(); } Double transform = arguments.size() > 1 ? (Double) arguments.get(1) : 0.; int length = processedArguments.get(0).getValues().length; for (TimeSeries ts : processedArguments) { for (int i = 0; i < length; i++) { ts.getValues()[i] = ts.getValues()[i] != null ? ts.getValues()[i] : transform; } ts.setName("transformNull(" + ts.getName() + "," + (DoubleMath.isMathematicalInteger(transform) ? Integer.toString(transform.intValue()) : transform ) + ")"); } return processedArguments; }
Example #6
Source File: Subscription.java From ua-server-sdk with GNU Affero General Public License v3.0 | 6 votes |
synchronized void startPublishingTimer() { if (state.get() == State.Closed) return; lifetimeCounter--; if (lifetimeCounter < 1) { logger.debug("[id={}] lifetime expired.", subscriptionId); setState(State.Closing); } else { long interval = DoubleMath.roundToLong(publishingInterval, RoundingMode.UP); subscriptionManager.getServer().getScheduledExecutorService().schedule( this::onPublishingTimer, interval, TimeUnit.MILLISECONDS ); } }
Example #7
Source File: FormattingRenamings.java From naturalize with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Predict the max-likelihood tokens given the ngrams. * * @param ngrams * @param alternatives * @return */ @Override public SortedSet<Renaming> calculateScores( final Multiset<NGram<String>> ngrams, final Set<String> alternatives, final Scope scope) { final SortedSet<Renaming> suggestions = Sets.newTreeSet(); for (final String alternative : alternatives) { double score = 0; for (final NGram<String> ngram : ngrams) { score += DoubleMath.log2(getNgramLM().getProbabilityFor( NGram.substituteTokenWith(ngram, WILDCARD_TOKEN, alternative))); } suggestions.add(new Renaming(alternative, -score, 1, null)); } return suggestions; }
Example #8
Source File: KafkaSingleLevelWorkUnitPacker.java From incubator-gobblin with Apache License 2.0 | 6 votes |
@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); } } if (!zeroSizeWorkUnit.getWorkUnits().isEmpty()) { workUnits.add(squeezeMultiWorkUnit(zeroSizeWorkUnit)); } } return worstFitDecreasingBinPacking(workUnits, numContainers); }
Example #9
Source File: GraphGenerator.java From ambiverse-nlu with Apache License 2.0 | 6 votes |
/** * Prunes candidates, keeping only the top K elements for each mention. K is * set in graphSettings. * * @param mention * * @return */ private Entities pruneCandidates(Mention mention) { Entities bestEntities = null; if (settings.getGraphSettings().shouldPruneCandidateEntities()) { int k = settings.getGraphSettings().getPruneCandidateThreshold(); Entities candidates = mention.getCandidateEntities(); if (candidates.size() > k) { Ordering<Entity> order = new Ordering<Entity>() { @Override public int compare(Entity e1, Entity e2) { return DoubleMath.fuzzyCompare(e1.getMentionEntitySimilarity(), e2.getMentionEntitySimilarity(), EPSILON); } }; List<Entity> topEntities = order.greatestOf(candidates, k); bestEntities = new Entities(); bestEntities.addAll(topEntities); } } return bestEntities; }
Example #10
Source File: BasicQueryByClass.java From geowave with Apache License 2.0 | 6 votes |
/** * Ignores 'default' indicator * * @param other * @return {@code true} if these constraints match the other constraints */ public boolean matches(final ConstraintData other) { if (this == other) { return true; } if (range == null) { if (other.range != null) { return false; } } else if (!DoubleMath.fuzzyEquals(range.getMin(), other.range.getMin(), DOUBLE_TOLERANCE) || !DoubleMath.fuzzyEquals(range.getMax(), other.range.getMax(), DOUBLE_TOLERANCE)) { return false; } return true; }
Example #11
Source File: BondFutureTradeCalculationsTest.java From Strata with Apache License 2.0 | 6 votes |
@Test public void test_pv01_quote() { ScenarioMarketData md = BondFutureTradeCalculationFunctionTest.marketData(); LegalEntityDiscountingProvider provider = LOOKUP.marketDataView(md.scenario(0)).discountingProvider(); DiscountingBondFutureTradePricer pricer = DiscountingBondFutureTradePricer.DEFAULT; PointSensitivities pvPointSens = pricer.presentValueSensitivity(RTRADE, provider); CurrencyParameterSensitivities pvParamSens = provider.parameterSensitivity(pvPointSens); CurrencyParameterSensitivities expectedPv01CalBucketed = MQ_CALC.sensitivity(pvParamSens.multipliedBy(1e-4), provider); MultiCurrencyAmount expectedPv01Cal = expectedPv01CalBucketed.total(); MultiCurrencyScenarioArray sumComputed = BondFutureTradeCalculations.DEFAULT.pv01MarketQuoteSum(RTRADE, LOOKUP, md); ScenarioArray<CurrencyParameterSensitivities> bucketedComputed = BondFutureTradeCalculations.DEFAULT.pv01MarketQuoteBucketed(RTRADE, LOOKUP, md); assertThat(sumComputed.getScenarioCount()).isEqualTo(1); assertThat(sumComputed.get(0).getCurrencies()).containsOnly(USD); assertThat(DoubleMath.fuzzyEquals( sumComputed.get(0).getAmount(USD).getAmount(), expectedPv01Cal.getAmount(USD).getAmount(), 1.0e-10)).isTrue(); assertThat(bucketedComputed.getScenarioCount()).isEqualTo(1); assertThat(bucketedComputed.get(0).equalWithTolerance(expectedPv01CalBucketed, 1.0e-10)).isTrue(); }
Example #12
Source File: CubeUtils.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * Flips parent's change ratio if the change ratios of current node and its parent are different. * * @param baselineValue the baseline value of a node. * @param currentValue the current value of a node. * @param ratio the (parent) ratio to be flipped. * * @return the ratio that has the same direction as the change direction of baseline and current value. */ public static double ensureChangeRatioDirection(double baselineValue, double currentValue, double ratio) { // case: value goes down but parent's value goes up if (DoubleMath.fuzzyCompare(baselineValue, currentValue, epsilon) > 0 && DoubleMath.fuzzyCompare(ratio, 1, epsilon) > 0) { if (Double.compare(ratio, 2) >= 0) { ratio = 2d - (ratio - ((long) ratio - 1)); } else { ratio = 2d - ratio; } // case: value goes up but parent's value goes down } else if (DoubleMath.fuzzyCompare(baselineValue, currentValue, epsilon) < 0 && DoubleMath.fuzzyCompare(ratio, 1, epsilon) < 0) { ratio = 2d - ratio; } // return the original ratio for other cases. return ratio; }
Example #13
Source File: AbstractIdentifierRenamings.java From naturalize with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public SortedSet<Renaming> calculateScores( final Multiset<NGram<String>> ngrams, final Set<String> alternatives, final Scope scope) { final SortedSet<Renaming> scoreMap = Sets.newTreeSet(); for (final String identifierName : alternatives) { double score = 0; for (final Entry<NGram<String>> ngram : ngrams.entrySet()) { try { final NGram<String> identNGram = NGram.substituteTokenWith( ngram.getElement(), WILDCARD_TOKEN, identifierName); final double ngramScore = scoreNgram(identNGram); score += DoubleMath.log2(ngramScore) * ngram.getCount(); } catch (final Throwable e) { LOGGER.warning(ExceptionUtils.getFullStackTrace(e)); } } scoreMap.add(new Renaming(identifierName, (addScopePriors( identifierName, scope) - score) / ngrams.size(), ngrams .size() / ngramLM.getN(), scope)); } return scoreMap; }
Example #14
Source File: ClusterIntegrationTestUtils.java From incubator-pinot with Apache License 2.0 | 6 votes |
private static boolean fuzzyCompare(String h2Value, String brokerValue, String connectionValue) { // Fuzzy compare expected value and actual value boolean error = false; if (NumberUtils.isParsable(h2Value)) { double expectedValue = Double.parseDouble(h2Value); double actualValueBroker = Double.parseDouble(brokerValue); double actualValueConnection = Double.parseDouble(connectionValue); if (!DoubleMath.fuzzyEquals(actualValueBroker, expectedValue, 1.0) || !DoubleMath .fuzzyEquals(actualValueConnection, expectedValue, 1.0)) { error = true; } } else { if (!h2Value.equals(brokerValue) || !h2Value.equals(connectionValue)) { error = true; } } return error; }
Example #15
Source File: PercentageEnricher.java From brooklyn-server with Apache License 2.0 | 5 votes |
@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); 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); }
Example #16
Source File: FstUtils.java From jopenfst with MIT License | 5 votes |
public static boolean arcEquals(Object thisArcObj, Object thatArcObj, double epsilon) { if (thisArcObj == thatArcObj) { return true; } if (thisArcObj == null || thatArcObj == null) { return false; } if (!Arc.class.isAssignableFrom(thisArcObj.getClass()) || !Arc.class.isAssignableFrom(thatArcObj.getClass())) { return false; } Arc thisArc = (Arc) thisArcObj; Arc thatArc = (Arc) thatArcObj; if (thisArc.getIlabel() != thatArc.getIlabel()) { return false; } if (thisArc.getNextState().getId() != thatArc.getNextState().getId()) { return false; } if (thisArc.getOlabel() != thatArc.getOlabel()) { return false; } if (!(thisArc.getWeight() == thatArc.getWeight())) { if (!DoubleMath.fuzzyEquals(thisArc.getWeight(), thatArc.getWeight(), epsilon)) { return false; } } return true; }
Example #17
Source File: GrammarPriorIdentifierRenaming.java From naturalize with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override protected double addScopePriors(final String identifierName, final Scope scope) { final double prob = gp.getMLProbability(identifierName, Pair.create(scope.astNodeType, scope.astParentNodeType)); if (prob > 0) { return -DoubleMath.log2(prob); } else if (!this.isTrueUNK(identifierName)) { return 100; } else { return 0; } }
Example #18
Source File: SnippetScorer.java From naturalize with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Get the probability of a specific renaming happening (taking at least * one of the suggestions). * * @param suggestions * @return */ public double getLogProbOfNotRenaming() { double logProbNotRename = 0; for (final Suggestion sg : suggestions) { final double pNotRename = sg.getProbNotRename(); checkArgument(pNotRename <= 1, pNotRename + " should be in the probability range"); checkArgument(pNotRename >= 0, pNotRename + " should be in the probability range"); logProbNotRename += DoubleMath.log2(pNotRename); } return logProbNotRename; }
Example #19
Source File: BondFutureTradeCalculationFunctionTest.java From Strata with Apache License 2.0 | 5 votes |
@Test public void test_pv01_quote() { BondFutureTradeCalculationFunction<BondFutureTrade> function = BondFutureTradeCalculationFunction.TRADE; ScenarioMarketData md = marketData(); LegalEntityDiscountingProvider provider = LOOKUP.marketDataView(md.scenario(0)).discountingProvider(); DiscountingBondFutureTradePricer pricer = DiscountingBondFutureTradePricer.DEFAULT; PointSensitivities pvPointSens = pricer.presentValueSensitivity(RTRADE, provider); CurrencyParameterSensitivities pvParamSens = provider.parameterSensitivity(pvPointSens); CurrencyParameterSensitivities expectedPv01CalBucketed = MQ_CALC.sensitivity(pvParamSens.multipliedBy(1e-4), provider); MultiCurrencyAmount expectedPv01Cal = expectedPv01CalBucketed.total(); Set<Measure> measures = ImmutableSet.of( Measures.PV01_MARKET_QUOTE_SUM, Measures.PV01_MARKET_QUOTE_BUCKETED); Map<Measure, Result<?>> computed = function.calculate(TRADE, measures, PARAMS, md, REF_DATA); MultiCurrencyScenarioArray sumComputed = (MultiCurrencyScenarioArray) computed.get(Measures.PV01_MARKET_QUOTE_SUM).getValue(); @SuppressWarnings("unchecked") ScenarioArray<CurrencyParameterSensitivities> bucketedComputed = (ScenarioArray<CurrencyParameterSensitivities>) computed.get(Measures.PV01_MARKET_QUOTE_BUCKETED).getValue(); assertThat(sumComputed.getScenarioCount()).isEqualTo(1); assertThat(sumComputed.get(0).getCurrencies()).containsOnly(USD); assertThat(DoubleMath.fuzzyEquals( sumComputed.get(0).getAmount(USD).getAmount(), expectedPv01Cal.getAmount(USD).getAmount(), 1.0e-10)).isTrue(); assertThat(bucketedComputed.getScenarioCount()).isEqualTo(1); assertThat(bucketedComputed.get(0).equalWithTolerance(expectedPv01CalBucketed, 1.0e-10)).isTrue(); }
Example #20
Source File: GeometricDistributionTest.java From api-mining with GNU General Public License v3.0 | 5 votes |
@Test public void testGetProb() { assertEquals(GeometricDistribution.getProb(1, .1), .1, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(1, .1), DoubleMath.log2(.1), 1E-10); assertEquals(GeometricDistribution.getProb(2, .1), .09, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(2, .1), DoubleMath.log2(.09), 1E-10); }
Example #21
Source File: ByteWritable.java From DataVec with Apache License 2.0 | 5 votes |
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 { return false; } return DoubleMath.fuzzyEquals(this.value, other, tolerance); }
Example #22
Source File: GeometricDistributionTest.java From tassal with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testGetProb() { assertEquals(GeometricDistribution.getProb(1, .1), .1, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(1, .1), DoubleMath.log2(.1), 1E-10); assertEquals(GeometricDistribution.getProb(2, .1), .09, 1E-10); assertEquals(GeometricDistribution.getLog2Prob(2, .1), DoubleMath.log2(.09), 1E-10); }
Example #23
Source File: ExpTrigsFunctions.java From symja_android_library with GNU General Public License v3.0 | 5 votes |
/** * Integer logarithm of <code>arg</code> for base <code>b</code>. Gives Log <sub>b</sub>(arg) or * <code>Log(arg)/Log(b)</code>. * * @param b * the base of the logarithm * @param arg * @return */ public static IExpr baseBLog(final IInteger b, final IInteger arg) { try { long l1 = b.toLong(); long l2 = arg.toLong(); if (l1 > 0L && l2 > 0L) { boolean inverse = false; if (l1 > l2) { long t = l2; l2 = l1; l1 = t; inverse = true; } double numericResult = Math.log(l2) / Math.log(l1); if (F.isNumIntValue(numericResult)) { long symbolicResult = DoubleMath.roundToLong(numericResult, RoundingMode.HALF_UP); if (inverse) { if (b.equals(arg.pow(symbolicResult))) { // cross checked result return F.QQ(1L, symbolicResult); } } else { if (arg.equals(b.pow(symbolicResult))) { // cross checked result return F.ZZ(symbolicResult); } } } } } catch (ArithmeticException ae) { // toLong() method failed } return F.NIL; }
Example #24
Source File: ProjectionRect.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Returns {@code true} if this bounding box contains {@code point}. * * @param point a point in projection coordinates. * @return {@code true} if this bounding box contains {@code point}. */ public boolean contains(ProjectionPoint point) { return DoubleMath.fuzzyCompare(point.getX(), getMinX(), 1e-6) >= 0 && DoubleMath.fuzzyCompare(point.getX(), getMaxX(), 1e-6) <= 0 && DoubleMath.fuzzyCompare(point.getY(), getMinY(), 1e-6) >= 0 && DoubleMath.fuzzyCompare(point.getY(), getMaxY(), 1e-6) <= 0; }
Example #25
Source File: ImpliedTrinomialTreeFxSingleBarrierOptionProductPricer.java From Strata with Apache License 2.0 | 5 votes |
private void validateData(ResolvedFxSingleBarrierOption option, RatesProvider ratesProvider, BlackFxOptionVolatilities volatilities, RecombiningTrinomialTreeData data) { ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption(); ArgChecker.isTrue(DoubleMath.fuzzyEquals(data.getTime(data.getNumberOfSteps()), volatilities.relativeTime(underlyingOption.getExpiry()), SMALL), "time to expiry mismatch between pricing option and trinomial tree data"); ArgChecker.isTrue(DoubleMath.fuzzyEquals(data.getSpot(), ratesProvider.fxRate(underlyingOption.getUnderlying().getCurrencyPair()), SMALL), "today's FX rate mismatch between rates provider and trinomial tree data"); }
Example #26
Source File: GeneralizedExtremeValueDistribution.java From Strata with Apache License 2.0 | 5 votes |
/** * Creates an instance. * * @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); }
Example #27
Source File: TimestampWatermark.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions * * @param diffInMilliSecs difference in range * @param hourInterval hour interval (ex: 4 hours) * @param maxIntervals max number of allowed partitions * @return calculated interval in hours */ private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) { long totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING); long totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING); if (totalIntervals > maxIntervals) { hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING); } return Ints.checkedCast(hourInterval); }
Example #28
Source File: GraphiteUtils.java From disthene-reader with MIT License | 5 votes |
public static String formatDoubleSpecialPlain(Double value) { BigDecimal bigDecimal = BigDecimal.valueOf(value); // do not do this for math integers if (!DoubleMath.isMathematicalInteger(value)) { // precision is just like in graphite (scale check redundant but let it be) if (bigDecimal.precision() > 12 && bigDecimal.scale() > 0) { int roundTo = bigDecimal.scale() - bigDecimal.precision() + 12 > 0 ? bigDecimal.scale() - bigDecimal.precision() + 12 : 0; bigDecimal = bigDecimal.setScale(roundTo, BigDecimal.ROUND_HALF_UP); } } return bigDecimal.stripTrailingZeros().toPlainString(); }
Example #29
Source File: AllocationIdUtil.java From proctor with Apache License 2.0 | 5 votes |
private static Map<Integer, Double> getBucketRatios(final List<Range> ranges) { final Map<Integer, Double> result = new HashMap<>(); for (final Range range : ranges) { final int bucket = range.getBucketValue(); final double length = range.getLength(); if ((bucket != -1) && !DoubleMath.fuzzyEquals(length, 0.0, 1e-6)) { final double total = result.getOrDefault(bucket, 0.0) + length; result.put(bucket, total); } } return ImmutableMap.copyOf(result); }
Example #30
Source File: StudentTOneTailedCriticalValueCalculator.java From Strata with Apache License 2.0 | 5 votes |
@Override public Double apply(Double x) { ArgChecker.notNull(x, "x"); ArgChecker.notNegative(x, "x"); if (DoubleMath.fuzzyEquals(x, 0.5, 1e-14)) { return 0.5; } return _dist.getInverseCDF(x); }