List of usage examples for java.lang Double POSITIVE_INFINITY
double POSITIVE_INFINITY
To view the source code for java.lang Double POSITIVE_INFINITY.
Click Source Link
From source file:com.opengamma.core.historicaltimeseries.impl.NonVersionedRedisHistoricalTimeSeriesSource.java
protected LocalDateDoubleTimeSeries loadTimeSeriesFromRedis(String redisKey, LocalDate start, LocalDate end) { // This is the only method that needs implementation. try (Timer.Context context = _getSeriesTimer.time()) { Jedis jedis = getJedisPool().getResource(); LocalDateDoubleTimeSeries ts = null; try {/*from w w w . j a v a2 s .c om*/ String redisHtsDaysKey = toRedisHtsDaysKey(redisKey); double min = Double.NEGATIVE_INFINITY; double max = Double.POSITIVE_INFINITY; if (start != null) { min = localDateToDouble(start); } if (end != null) { max = localDateToDouble(end); } Set<String> dateTexts = jedis.zrangeByScore(redisHtsDaysKey, min, max); if (!dateTexts.isEmpty()) { String redisHtsDatapointKey = toRedisHtsDatapointKey(redisKey); List<String> valueTexts = jedis.hmget(redisHtsDatapointKey, dateTexts.toArray(new String[dateTexts.size()])); List<Integer> times = Lists.newArrayListWithCapacity(dateTexts.size()); List<Double> values = Lists.newArrayListWithCapacity(valueTexts.size()); Iterator<String> dateItr = dateTexts.iterator(); Iterator<String> valueItr = valueTexts.iterator(); while (dateItr.hasNext()) { String dateAsIntText = dateItr.next(); String valueText = StringUtils.trimToNull(valueItr.next()); if (valueText != null) { times.add(Integer.parseInt(dateAsIntText)); values.add(Double.parseDouble(valueText)); } } ts = ImmutableLocalDateDoubleTimeSeries.of( ArrayUtils.toPrimitive(times.toArray(new Integer[times.size()])), ArrayUtils.toPrimitive(values.toArray(new Double[values.size()]))); } getJedisPool().returnResource(jedis); } catch (Exception e) { s_logger.error("Unable to load points from redis for " + redisKey, e); getJedisPool().returnBrokenResource(jedis); throw new OpenGammaRuntimeException("Unable to load points from redis for " + redisKey, e); } return ts; } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Object, java.lang.Number, java.lang.Class)}. *///from ww w . j a v a 2 s . c o m @SuppressWarnings("unchecked") @Test public void testAddObjectNumberClassOfT() { assertEquals("null", null, add(null, null, null)); assertEquals("null", null, add("123.456", null, null)); assertEquals("null", null, add("123.456", 1, null)); assertEquals("null", null, add("", 10, null)); assertEquals("null", null, add(null, 10, null)); assertEquals("null", null, add(123.456, 10, null)); assertEquals("123 + .456: Float", (Object) 123.456f, add(123, .456, Float.class)); assertEquals("123 + .456: Float", (Object) Float.class, add(123, .456, Float.class).getClass()); assertEquals("123 + .456: Float", (Object) Float.class, add(123L, .456d, Float.class).getClass()); for (Class<?> type : NUMBERS) { try { Object expected = null; Class<? extends Number> typeOfN = (Class<? extends Number>) type; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); assertEquals("null: default: " + type.getSimpleName(), valueOf(null, typeOfN), add(null, null, typeOfN)); assertEquals("123.456: " + type.getSimpleName(), valueOf(123 + .456, typeOfN), add("123", .456, typeOfN)); assertEquals("NaN + 123: " + type.getSimpleName(), valueOf(123, typeOfN), add("NaN", 123, typeOfN)); assertEquals("123 + NaN: " + type.getSimpleName(), valueOf("123", typeOfN), add("123", Float.NaN, typeOfN)); assertEquals("invalid + 123: " + type.getSimpleName(), valueOf(123, typeOfN), add("not a number", 123, typeOfN)); if (Double.class.equals(wrapper)) { expected = (wrapper.getField("MAX_VALUE").getDouble(null) * -1) + 123; } else if (Float.class.equals(wrapper)) { expected = Float.NEGATIVE_INFINITY; } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = valueOf("-Infinity", typeOfN); } else { expected = INFINITY_DOUBLE.negate().add(BigDecimal.valueOf(123)); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("-Infinity: Double: + 123: " + type.getSimpleName(), expected, add("-Infinity", 123, typeOfN)); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = valueOf("Infinity", typeOfN); } else { expected = INFINITY_DOUBLE.add(BigDecimal.valueOf(123)); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("Infinity: Double: + 123: " + type.getSimpleName(), expected, add("Infinity", 123, typeOfN)); if (Double.class.equals(wrapper)) { expected = (wrapper.getField("MAX_VALUE").getDouble(null) * -1) + 123; } else if (Float.class.equals(wrapper)) { expected = Float.NEGATIVE_INFINITY; } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = valueOf("-Infinity", typeOfN); } else { expected = INFINITY_DOUBLE.negate().add(BigDecimal.valueOf(123)); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("123 - Infinity: Double: " + type.getSimpleName(), expected, add("123", Double.NEGATIVE_INFINITY, typeOfN)); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = valueOf("Infinity", typeOfN); } else { expected = INFINITY_DOUBLE.add(BigDecimal.valueOf(123)); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("123 + Infinity: Double: " + type.getSimpleName(), expected, add("123", Double.POSITIVE_INFINITY, typeOfN)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }
From source file:beast.evolution.tree.partitioned.IndividualSEIR.java
public double evaluateLogP() { // try { // PrintStream firstSteam = new PrintStream("tt.nex"); ///* w w w .j a v a2s . c o m*/ // PartitionedTreeLogger.debugLog(tree, 0, false, firstSteam); // } catch (FileNotFoundException e){ // e.printStackTrace(); // } double transLogProb = 0; double rate = baseTransmissionRate.getValue(); ArrayList<ClinicalCase> previouslyInfectious = new ArrayList<>(); double currentEventTime; boolean first = true; for (TreeEvent event : sortedTreeEvents) { currentEventTime = event.getTime(); ClinicalCase thisCase = event.getCase(); if (event.getType() == EventType.INFECTION) { if (first) { // index infection if (indexCasePrior != null) { transLogProb += Math.log(indexCasePrior.get(thisCase)); } if (initialInfectionTimePrior != null) { transLogProb += initialInfectionTimePrior.logDensity(currentEventTime); } if (!hasLatentPeriods) { previouslyInfectious.add(thisCase); } first = false; } else { ClinicalCase infector = event.getInfector(); if (thisCase.wasEverInfected()) { if (previouslyInfectious.contains(thisCase)) { return Double.NEGATIVE_INFINITY; } if (event.getTime() > thisCase.getEndTime()) { return Double.NEGATIVE_INFINITY; } if (infector.getEndTime() < event.getTime()) { return Double.NEGATIVE_INFINITY; } if (getInfectiousTime(infector) > event.getTime()) { return Double.NEGATIVE_INFINITY; } if (!previouslyInfectious.contains(infector)) { throw new RuntimeException("Infector not previously infected"); } } // no other previously infectious case has infected this case... for (ClinicalCase nonInfector : previouslyInfectious) { double timeDuringWhichNoInfection; if (nonInfector.getEndTime() < event.getTime()) { timeDuringWhichNoInfection = nonInfector.getEndTime() - getInfectiousTime(nonInfector); } else { timeDuringWhichNoInfection = event.getTime() - getInfectiousTime(nonInfector); } if (timeDuringWhichNoInfection < 0) { throw new RuntimeException("negative time"); } double transRate = rate; if (hasGeography) { try { transRate *= kernel.getValue((GeographicallyLocatedClinicalCase) thisCase, (GeographicallyLocatedClinicalCase) nonInfector); } catch (FunctionEvaluationException e) { e.printStackTrace(); } } transLogProb += -transRate * timeDuringWhichNoInfection; } // ...until the end if (thisCase.wasEverInfected()) { double transRate = rate; if (hasGeography) { try { transRate *= kernel.getValue((GeographicallyLocatedClinicalCase) thisCase, (GeographicallyLocatedClinicalCase) infector); } catch (FunctionEvaluationException e) { e.printStackTrace(); } } transLogProb += Math.log(transRate); } if (!hasLatentPeriods) { previouslyInfectious.add(thisCase); } } } else if (event.getType() == EventType.INFECTIOUSNESS) { if (event.getTime() < Double.POSITIVE_INFINITY) { if (event.getTime() > event.getCase().getEndTime()) { return Double.NEGATIVE_INFINITY; } if (first) { throw new RuntimeException("First event is not an infection"); } previouslyInfectious.add(thisCase); } } } double periodsLogProb = 0; for (DurationDistribution category : infectiousCategories) { if (category.hasProbability()) { List<ClinicalCase> relevantCases = new ArrayList<>(); for (ClinicalCase aCase : outbreak.getCases()) { if (getInfectiousCategory(aCase) == category) { relevantCases.add(aCase); } } Double[] infectiousPeriods = new Double[relevantCases.size()]; for (int i = 0; i < infectiousPeriods.length; i++) { infectiousPeriods[i] = relevantCases.get(i).getEndTime() - getInfectiousTime(relevantCases.get(i)); } RealParameter collectionOfValues = new RealParameter(infectiousPeriods); periodsLogProb += category.getLogProbability(collectionOfValues); } } // just reject states where these round to +INF if (transLogProb == Double.POSITIVE_INFINITY) { System.out.println("TransLogProb +INF"); return Double.NEGATIVE_INFINITY; } if (periodsLogProb == Double.POSITIVE_INFINITY) { System.out.println("PeriodsLogProb +INF"); return Double.NEGATIVE_INFINITY; } logP = periodsLogProb + transLogProb; return logP; }
From source file:net.sf.json.TestJSONArray.java
public void testConstructor_primitive_array_double_Infinity() { try {//from ww w. j a va 2 s .c o m JSONArray.fromObject(new double[] { Double.NEGATIVE_INFINITY }); fail("Should have thrown a JSONException"); } catch (JSONException expected) { // OK } try { JSONArray.fromObject(new double[] { Double.POSITIVE_INFINITY }); fail("Should have thrown a JSONException"); } catch (JSONException expected) { // OK } }
From source file:clus.algo.tdidt.tune.CDTuneSizeConstrPruning.java
public int findOptimalSize(ArrayList graph, boolean shouldBeLow) { double best_value = shouldBeLow ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; int best_index = -1; for (int i = 0; i < graph.size(); i++) { SingleStatList elem = (SingleStatList) graph.get(i); if (shouldBeLow) { if (elem.getY() < best_value) { best_value = elem.getY(); best_index = i;/*w w w.j a v a 2 s.c o m*/ } } else { if (elem.getY() > best_value) { best_value = elem.getY(); best_index = i; } } } if (best_index == -1) { return 1; } // double max_diff = getRange(graph); SingleStatList best_elem = (SingleStatList) graph.get(best_index); System.out.print("[" + best_elem.getX() + "," + best_elem.getY() + "]"); SingleStatList result = best_elem; int pos = best_index - 1; while (pos >= 0) { SingleStatList prev_elem = (SingleStatList) graph.get(pos); if (prev_elem.getX() >= 3 && Math.abs(prev_elem.getY() - best_elem.getY()) < m_RelErrAcc) { result = prev_elem; System.out.print(" < " + prev_elem.getX()); } pos--; } return (int) result.getX(); }
From source file:com.rapidminer.gui.plotter.charts.MultipleScatterPlotter.java
private void prepareData() { idMap.clear();//from w w w . j av a2s . c o m this.plotIndexToColumnIndexMap.clear(); dataSet = new DefaultXYDataset(); if (xAxis >= 0) { Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>(); Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>(); synchronized (dataTable) { for (int column = 0; column < plotColumns.length; column++) { if (plotColumns[column]) { plotIndexToColumnIndexMap.add(column); String columnName = this.dataTable.getColumnName(column); Iterator<DataTableRow> i = this.dataTable.iterator(); int index = 0; while (i.hasNext()) { DataTableRow row = i.next(); double xValue = row.getValue(xAxis); double yValue = row.getValue(column); if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) { addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, columnName); } index++; } } } } double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, List<double[]>> entry = i.next(); List<double[]> dataList = entry.getValue(); Iterator<double[]> j = dataList.iterator(); while (j.hasNext()) { double[] current = j.next(); minX = Math.min(minX, current[0]); maxX = Math.max(maxX, current[0]); minY = Math.min(minY, current[1]); maxY = Math.max(maxY, current[1]); } } Random jitterRandom = new Random(2001); double oldXRange = maxX - minX; double oldYRange = maxY - minY; if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) { oldXRange = 0; } if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) { oldYRange = 0; } i = dataCollection.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, List<double[]>> entry = i.next(); String seriesName = entry.getKey(); List<double[]> dataList = entry.getValue(); double[][] data = new double[2][dataList.size()]; int listCounter = 0; Iterator<double[]> j = dataList.iterator(); while (j.hasNext()) { double[] current = j.next(); data[0][listCounter] = current[0]; data[1][listCounter] = current[1]; if (this.jitterAmount > 0) { double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian(); double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian(); data[0][listCounter] += pertX; data[1][listCounter] += pertY; } listCounter++; } ((DefaultXYDataset) dataSet).addSeries(seriesName, data); } int seriesCounter = 0; Iterator<List<String>> v = idCollection.values().iterator(); while (v.hasNext()) { List<String> idList = v.next(); int itemCounter = 0; Iterator<String> j = idList.iterator(); while (j.hasNext()) { idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next()); } seriesCounter++; } } }
From source file:cloudnet.examples.elasticity.bn.DistrHelper.java
private static double[] getWorkloadDistrByAverageValue(double time) { double[] result = new double[WorkloadLevel.AllWithOverusage().length]; int index = 0; double levelStep = (100.0 / WorkloadLevel.All().length); // get percent double percent = (100 * time) / (double) MaxSlaViolationTime; //specify distr NormalDistribution d = new NormalDistribution(percent / 2, percent / 6); // get probabilites double[] probabilities = new double[WorkloadLevel.AllWithOverusage().length]; double maxp = 0.0d; for (int l = 0; l < WorkloadLevel.AllWithOverusage().length - 1; l++) { double p = d.probability(l * levelStep, (l + 1) * levelStep); probabilities[l] = p;/*from w w w .j av a2s . c om*/ maxp = FastMath.max(maxp, p); } probabilities[WorkloadLevel.AllWithOverusage().length - 1] = d .probability(WorkloadLevel.AllWithOverusage().length * levelStep, Double.POSITIVE_INFINITY); if (maxp != 0.0d) { // and insert their normalized values into result array double sum = 1.0d; for (int l = 0; l < probabilities.length - 1; l++) { double newValue = FastMath.min(sum, probabilities[l] / maxp); result[index++] = newValue; sum -= newValue; } result[index++] = sum; Ensure.GreaterThanOrEquals(sum, 0d, "sum of probabilities"); } else { // if no max probability found, just put 1.0 for the closest level // let say, if percent = 42 and there are 10 levels, levelIndex = would be 4 int levelIndex = (int) FastMath.floor(percent / levelStep); if (levelIndex > WorkloadLevel.All().length) { levelIndex = WorkloadLevel.AllWithOverusage().length - 1; } Ensure.GreaterThanOrEquals(levelIndex, 0, "levelIndex"); for (int l = 0; l < WorkloadLevel.AllWithOverusage().length; l++) { if (l == levelIndex) { result[index++] = 1.0d; } else { result[index++] = 0.0d; } } } return result; }
From source file:io.druid.server.coordinator.CostBalancerStrategy.java
protected double computeCost(final DataSegment proposalSegment, final ServerHolder server, final boolean includeCurrentServer) { final long proposalSegmentSize = proposalSegment.getSize(); // (optional) Don't include server if it is already serving segment if (!includeCurrentServer && server.isServingSegment(proposalSegment)) { return Double.POSITIVE_INFINITY; }//w w w. j av a 2s . co m // Don't calculate cost if the server doesn't have enough space or is loading the segment if (proposalSegmentSize > server.getAvailableSize() || server.isLoadingSegment(proposalSegment)) { return Double.POSITIVE_INFINITY; } // The contribution to the total cost of a given server by proposing to move the segment to that server is... double cost = 0d; // the sum of the costs of other (exclusive of the proposalSegment) segments on the server cost += computeJointSegmentsCost(proposalSegment, Iterables.filter( server.getServer().getSegments().values(), Predicates.not(Predicates.equalTo(proposalSegment)))); // plus the costs of segments that will be loaded cost += computeJointSegmentsCost(proposalSegment, server.getPeon().getSegmentsToLoad()); return cost; }
From source file:com.clust4j.algo.KMedoids.java
private ClusterAssignments assignClosestMedoid(int[] medoidIdcs) { double minDist; boolean all_tied = true; int nearest, rowIdx, colIdx; final int[] assn = new int[m]; final double[] costs = new double[m]; for (int i = 0; i < m; i++) { boolean is_a_medoid = false; minDist = Double.POSITIVE_INFINITY; /*//from w w w . j a v a 2 s . c o m * The dist_mat is already computed. We just need to traverse * the upper triangular matrix and identify which corresponding * minimum distance per record. */ nearest = -1; for (int medoid : medoidIdcs) { // Corner case: i is a medoid if (i == medoid) { nearest = medoid; minDist = dist_mat[i][i]; is_a_medoid = true; break; } rowIdx = FastMath.min(i, medoid); colIdx = FastMath.max(i, medoid); if (dist_mat[rowIdx][colIdx] < minDist) { minDist = dist_mat[rowIdx][colIdx]; nearest = medoid; } } /* * If all of the distances are equal, we can end up with a -1 idx... */ if (-1 == nearest) nearest = medoidIdcs[getSeed().nextInt(k)]; // select random nearby if (!is_a_medoid) all_tied = false; assn[i] = nearest; costs[i] = minDist; } /* * If everything is tied, we need to bail. Shouldn't happen, now * that we explicitly check earlier on... but we can just label from * a singular K at this point. */ if (all_tied) { throw new IllegalClusterStateException("entirely " + "stochastic process: all distances are equal"); } return new ClusterAssignments(assn, costs); }
From source file:edu.cmu.tetrad.util.StatUtils.java
/** * @param array a double array. * @param N the number of values of array which should be * considered./*from w w w. j a v a 2 s .co m*/ * @param quartileNumber 1, 2, or 3. * @return the requested quartile of the first N values in this array. */ public static double quartile(double array[], int N, int quartileNumber) { if ((quartileNumber < 1) || (quartileNumber > 3)) { throw new IllegalArgumentException("StatUtils.quartile: " + "Quartile number must be 1, 2, or 3."); } double a[] = new double[N + 1]; System.arraycopy(array, 0, a, 0, N); a[N] = Double.POSITIVE_INFINITY; double v, t; int i, j, l = 0; int r = N - 1; // find the two indexes k1 and k2 (possibly equal) which need // to be interpolated to get the quartile, being careful to // zero-index. Also find interpolation ratio. double doubleIndex = (quartileNumber / 4.0) * (N + 1.0) - 1; double ratio = doubleIndex - (int) (doubleIndex); int k1 = (int) Math.floor(doubleIndex); int k2 = (int) Math.ceil(doubleIndex); // partially sort array a[] to find k1 and k2 while (r > l) { v = a[l]; i = l; j = r + 1; for (;;) { while (a[++i] < v) { } while (a[--j] > v) { } if (i >= j) { break; } t = a[i]; a[i] = a[j]; a[j] = t; } t = a[j]; a[j] = a[l]; a[l] = t; if (j <= k1) { l = j + 1; } if (j >= k2) { r = j - 1; } } // return the interpolated value. return (a[k1] + ratio * (a[k2] - a[k1])); }