List of usage examples for java.lang Number doubleValue
public abstract double doubleValue();
From source file:ai.grakn.test.graql.analytics.ScalingTestIT.java
/** * This test creates a graph of S*N*2 entities in total where: S is the total number of steps and N is the number of * entities per step. Each entity has a single numeric resource attached with the values chosen so that each size * of graph results in different values for the min, max, mean, sum, std. The median value always remains the same * but because the graph is growing, this in itself is a good test of median. The values follow the pattern: * * STEP g=1: 5 6 14 16/*from www . jav a 2 s . c o m*/ * STEP g=2: 3 4 5 6 14 16 18 20 * STEP g=3: 1 2 3 4 5 6 14 16 18 20 22 24 * * for S = 3, N = 2. * * To generate the sequence there are two recursive formulae, one for the lower half of values v_m, another for the * upper half V_m: * * v_m+1 = v_m - 1, v_1 = S*N * V_m+1 = V_m + 2, V_1 = (S*N + 1)*2 * * The sum of these values at STEP g is given by the formula: * * sum(g) = g*N(1/2 + g*N/2 + 3*S*N + 1) * * The min: * * min(g) = (S-g)*N + 1 * * The max: * * max(g) = 2*N*(g+S) * * The mean: * * mean(g) = sum(g)/(2*g*N) * * The std: * * ss = 5*(1/6 + SN + S^2*N^2) + 3*g*N(1/2 +S*N) + 5*g^2*N^2/3 * * std(g) = sqrt(ss/2 - mean(g)) * * The median: * * median(g) = S*N */ @Ignore @Test public void testStatisticsWithConstantDegree() throws IOException, InvalidGraphException { int totalSteps = NUM_DIVS; int nodesPerStep = MAX_SIZE / NUM_DIVS / 2; int v_m = totalSteps * nodesPerStep; int V_m = 2 * (totalSteps * nodesPerStep + 1); // detail methods that must be executed when testing List<String> methods = new ArrayList<>(); Map<String, Function<ComputeQueryBuilderImplMock, Optional>> statisticsMethods = new HashMap<>(); Map<String, Consumer<Number>> statisticsAssertions = new HashMap<>(); methods.add("testStatisticsWithConstantDegreeSum.txt"); statisticsMethods.put(methods.get(0), queryBuilder -> getSumQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); methods.add("testStatisticsWithConstantDegreeMin.txt"); statisticsMethods.put(methods.get(1), queryBuilder -> getMinQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); methods.add("testStatisticsWithConstantDegreeMax.txt"); statisticsMethods.put(methods.get(2), queryBuilder -> getMaxQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); methods.add("testStatisticsWithConstantDegreeMean.txt"); statisticsMethods.put(methods.get(3), queryBuilder -> getMeanQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); methods.add("testStatisticsWithConstantDegreeStd.txt"); statisticsMethods.put(methods.get(4), queryBuilder -> getStdQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); methods.add("testStatisticsWithConstantDegreeMedian.txt"); statisticsMethods.put(methods.get(5), queryBuilder -> getMedianQuery(queryBuilder) .of(Collections.singleton(TypeLabel.of("degree"))).execute()); // load up the result files Map<String, CSVPrinter> printers = new HashMap<>(); for (String method : methods) { printers.put(method, createCSVPrinter(method)); } // create the ontology simpleOntology(keyspace); BatchMutatorClient loader = new BatchMutatorClient(Grakn.DEFAULT_URI, keyspace); for (int g = 1; g < totalSteps + 1; g++) { LOGGER.info("starting step: " + g); // load data LOGGER.info("start loading data"); for (int m = 1; m < nodesPerStep + 1; m++) { loader.add(insert(var().isa("thing").has("degree", v_m))); loader.add(insert(var().isa("thing").has("degree", V_m))); v_m--; V_m += 2; } loader.waitToFinish(); LOGGER.info("stop loading data"); GraknGraph graph = Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE); LOGGER.info("gremlin count is: " + graph.admin().getTinkerTraversal().count().next()); graph.close(); for (String method : methods) { printers.get(method).print(2 * g * nodesPerStep); LOGGER.info("starting to execute: " + method); for (int workerNumber : workerNumbers) { LOGGER.info("starting with: " + workerNumber + " threads"); // configure assertions final long currentG = (long) g; final long N = (long) nodesPerStep; final long S = (long) totalSteps; statisticsAssertions.put(methods.get(0), number -> { Number sum = currentG * N * (1L + currentG * N + 6L * S * N + 2L) / 2L; assertEquals(sum.doubleValue(), number.doubleValue(), 1E-9); }); statisticsAssertions.put(methods.get(1), number -> { Number min = (S - currentG) * N + 1L; assertEquals(min.doubleValue(), number.doubleValue(), 1E-9); }); statisticsAssertions.put(methods.get(2), number -> { Number max = (S + currentG) * N * 2D; assertEquals(max.doubleValue(), number.doubleValue(), 1E-9); }); statisticsAssertions.put(methods.get(3), number -> { double mean = meanOfSequence(currentG, N, S); assertEquals(mean, number.doubleValue(), 1E-9); }); statisticsAssertions.put(methods.get(4), number -> { double std = stdOfSequence(currentG, N, S); assertEquals(std, number.doubleValue(), 1E-9); }); statisticsAssertions.put(methods.get(5), number -> { Number median = S * N; assertEquals(median.doubleValue(), number.doubleValue(), 1E-9); }); long averageTime = 0; for (int i = 0; i < REPEAT; i++) { LOGGER.info("starting repeat: " + i); // check stats are correct Long startTime = System.currentTimeMillis(); Number currentResult = (Number) statisticsMethods.get(method) .apply(getComputeQueryBuilder(Grakn.DEFAULT_URI, keyspace, workerNumber)).get(); Long stopTime = System.currentTimeMillis(); averageTime += stopTime - startTime; statisticsAssertions.get(method).accept(currentResult); } averageTime /= REPEAT * 1000; printers.get(method).print(averageTime); } printers.get(method).println(); printers.get(method).flush(); } } for (String method : methods) { printers.get(method).flush(); printers.get(method).close(); } GraknGraph graph = Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE); graph.admin().delete(); }
From source file:de.tuberlin.uebb.jbop.optimizer.controlflow.ConstantIfInliner.java
private Number calculateOparator(final AbstractInsnNode node1, final Number op1, final Number op2) { Number newNumber = op1;/*from w w w. j a va2 s .co m*/ if (isCompare(node1)) { switch (node1.getOpcode()) { case Opcodes.DCMPG: case Opcodes.DCMPL: newNumber = Double.valueOf(op2.doubleValue() - op1.doubleValue()); break; case Opcodes.FCMPG: case Opcodes.FCMPL: newNumber = Float.valueOf(op2.floatValue() - op1.floatValue()); break; case Opcodes.LCMP: newNumber = Long.valueOf(op2.longValue() - op1.longValue()); break; default: newNumber = op1; } } return newNumber; }
From source file:org.jfree.chart.demo.ExtendedStackedBarRenderer.java
/** * Returns true if the specified item is the last positive value for that category. * // w ww . j a va 2 s .c o m * @param dataset the dataset. * @param row the row (series). * @param column the column (category). * * @return a boolean. */ private boolean isLastPositiveItem(final CategoryDataset dataset, final int row, final int column) { boolean result = true; Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return false; // value is null } for (int r = row + 1; r < dataset.getRowCount(); r++) { dataValue = dataset.getValue(r, column); if (dataValue != null) { result = result && (dataValue.doubleValue() <= 0.0); } } return result; }
From source file:org.jfree.chart.demo.ExtendedStackedBarRenderer.java
/** * Returns true if the specified item is the last negative value for that category. * //from w w w. ja v a2 s. co m * @param dataset the dataset. * @param row the row (series). * @param column the column (category). * * @return a boolean. */ private boolean isLastNegativeItem(final CategoryDataset dataset, final int row, final int column) { boolean result = true; Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return false; // value is null } for (int r = row + 1; r < dataset.getRowCount(); r++) { dataValue = dataset.getValue(r, column); if (dataValue != null) { result = result && (dataValue.doubleValue() >= 0.0); } } return result; }
From source file:org.f3.tools.framework.Reporter.java
private String generateImage(String refName, String name, Number changeFactor) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(changeFactor, 0, 0); JFreeChart chart = ChartFactory.createBarChart("", "", "%change", dataset, PlotOrientation.HORIZONTAL, false, false, false);/*w ww . j a v a2s .c o m*/ try { Color bgcolor = null; double value = changeFactor.doubleValue(); if (value == Double.POSITIVE_INFINITY || value == Double.NEGATIVE_INFINITY) { bgcolor = Color.YELLOW; } else if (value > 5) { bgcolor = Color.GREEN; } else if (value >= -5 && value <= 5) { bgcolor = Color.WHITE; } else { bgcolor = Color.RED; } chart.setBackgroundPaint(bgcolor); File dirFile = new File(IMAGE_DIRNAME); if (!dirFile.exists()) { dirFile.mkdirs(); } File ofile = new File(dirFile, name); ChartUtilities.saveChartAsPNG(ofile, chart, 300, 100); return getImageRef(refName, name); } catch (IOException ioe) { Utils.logger.severe(ioe.getMessage()); } return null; }
From source file:org.trade.ui.chart.renderer.CandleRenderer.java
private void configureToolTips() { setBaseToolTipGenerator(new XYToolTipGenerator() { public String generateToolTip(XYDataset dataset, int series, int item) { StringBuilder result = new StringBuilder("<html>"); if (dataset instanceof CandleDataset) { CandleDataset d = (CandleDataset) dataset; Number time = d.getX(series, item); Number high = d.getHigh(series, item); Number low = d.getLow(series, item); Number open = d.getOpen(series, item); Number close = d.getClose(series, item); Number vwap = d.getVwap(series, item); Number volume = d.getVolume(series, item); result.append("<b>Open:</b> ").append(new Money(open.doubleValue())).append("<br/>"); result.append("<b>High:</b> ").append(new Money(high.doubleValue())).append("<br/>"); result.append("<b>Low:</b> ").append(new Money(low.doubleValue())).append("<br/>"); result.append("<b>Close:</b> ").append(new Money(close.doubleValue())).append("<br/>"); result.append("<b>Vwap:</b> ").append(new Money(vwap.doubleValue())).append("<br/>"); result.append("<b>Volume:</b> ").append(new Quantity(volume.intValue())).append("<br/>"); result.append("<b>Date:</b> ").append(TOOLTIP_DATE_FORMAT.format(time)).append("<br/>"); }/*from w w w .j av a 2s . c o m*/ return result.toString(); } }); }
From source file:gate.termraider.output.PairCsvGenerator.java
private void generateCsv(PrintWriter writer, Number threshold) { Map<UnorderedTermPair, Double> scores = pairbank.getScores(); List<UnorderedTermPair> pairs = new ArrayList<UnorderedTermPair>(scores.keySet()); Collections.sort(pairs, new TermPairComparatorByDescendingScore(scores)); addComment("threshold = " + threshold); addComment("Unfiltered nbr of pairs = " + pairs.size()); int written = 0; writeHeader(writer);// www. j a va2 s . c om for (UnorderedTermPair pair : pairs) { double score = scores.get(pair); if (score < threshold.doubleValue()) { break; } writeContent(writer, pair.getTerm0(), pair.getTerm1(), score, pairbank.getDocumentCount(pair), pairbank.getPairCount(pair)); } addComment("Filtered nbr of pairs = " + written); }
From source file:moe.encode.airblock.commands.arguments.types.PrimitiveParser.java
@Override public Object convert(Executor executor, ArgumentConverter parser, Type type, String value) { Class<?> cls = ReflectionUtils.toClass(type); if (ClassUtils.isPrimitiveWrapper(cls)) cls = ClassUtils.wrapperToPrimitive(cls); if (cls.equals(boolean.class)) return this.isTrue(executor, value); else if (cls.equals(char.class)) { if (value.length() > 0) throw new NumberFormatException("Character arguments cannot be longer than one characters"); return value.charAt(0); }// ww w .j a va2 s. c o m // Get the locale of the user and get a number-format according to it. LocaleResolver resolver = TranslationManager.getResolver(executor); Locale locale; if (resolver != null) locale = resolver.getLocale(); else locale = Locale.ENGLISH; NumberFormat nf = NumberFormat.getNumberInstance(locale); nf.setGroupingUsed(true); // Parse the value. Number result; try { result = nf.parse(value); } catch (ParseException e) { NumberFormatException nfe = new NumberFormatException("Invalid number"); nfe.initCause(e); throw nfe; } // Returns the value in the correct type. if (cls.equals(int.class)) return result.intValue(); else if (cls.equals(float.class)) return result.floatValue(); else if (cls.equals(double.class)) return result.doubleValue(); else if (cls.equals(byte.class)) return result.byteValue(); else if (cls.equals(short.class)) return result.shortValue(); else if (cls.equals(long.class)) return result.longValue(); throw new NumberFormatException("Unknown primitive type."); }
From source file:com.jayway.jsonpath.Criteria.java
boolean singleObjectApply(Map<String, Object> map) { for (CriteriaType key : this.criteria.keySet()) { Object actualVal = map.get(this.key); Object expectedVal = this.criteria.get(key); if (CriteriaType.GT.equals(key)) { if (expectedVal == null || actualVal == null) { return false; }//from w ww.j a v a2 s. com Number expectedNumber = (Number) expectedVal; Number actualNumber = (Number) actualVal; return (actualNumber.doubleValue() > expectedNumber.doubleValue()); } else if (CriteriaType.GTE.equals(key)) { if (expectedVal == null || actualVal == null) { return false; } Number expectedNumber = (Number) expectedVal; Number actualNumber = (Number) actualVal; return (actualNumber.doubleValue() >= expectedNumber.doubleValue()); } else if (CriteriaType.LT.equals(key)) { if (expectedVal == null || actualVal == null) { return false; } Number expectedNumber = (Number) expectedVal; Number actualNumber = (Number) actualVal; return (actualNumber.doubleValue() < expectedNumber.doubleValue()); } else if (CriteriaType.LTE.equals(key)) { if (expectedVal == null || actualVal == null) { return false; } Number expectedNumber = (Number) expectedVal; Number actualNumber = (Number) actualVal; return (actualNumber.doubleValue() <= expectedNumber.doubleValue()); } else if (CriteriaType.NE.equals(key)) { if (expectedVal == null && actualVal == null) { return false; } if (expectedVal == null) { return true; } else { return !expectedVal.equals(actualVal); } } else if (CriteriaType.IN.equals(key)) { Collection exp = (Collection) expectedVal; return exp.contains(actualVal); } else if (CriteriaType.NIN.equals(key)) { Collection exp = (Collection) expectedVal; return !exp.contains(actualVal); } else if (CriteriaType.ALL.equals(key)) { Collection exp = (Collection) expectedVal; Collection act = (Collection) actualVal; return act.containsAll(exp); } else if (CriteriaType.SIZE.equals(key)) { int exp = (Integer) expectedVal; List act = (List) actualVal; return (act.size() == exp); } else if (CriteriaType.EXISTS.equals(key)) { boolean exp = (Boolean) expectedVal; boolean act = map.containsKey(this.key); return act == exp; } else if (CriteriaType.TYPE.equals(key)) { Class<?> exp = (Class<?>) expectedVal; Class<?> act = null; if (map.containsKey(this.key)) { Object actVal = map.get(this.key); if (actVal != null) { act = actVal.getClass(); } } if (act == null) { return false; } else { return act.equals(exp); } } else if (CriteriaType.REGEX.equals(key)) { Pattern exp = (Pattern) expectedVal; String act = (String) actualVal; if (act == null) { return false; } return exp.matcher(act).matches(); } else { throw new UnsupportedOperationException("Criteria type not supported: " + key.name()); } } if (isValue != NOT_SET) { if (isValue instanceof Collection) { Collection<Criteria> cs = (Collection<Criteria>) isValue; for (Criteria crit : cs) { for (Criteria c : crit.criteriaChain) { if (!c.singleObjectApply(map)) { return false; } } } return true; } else { if (isValue == null) { return (map.get(key) == null); } else { return isValue.equals(map.get(key)); } } } else { } return true; }
From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java
private AbstractInsnNode handleDiv(final int opcode, final Number one, final Number two) { final Number number; switch (opcode) { case IDIV://from ww w . j av a 2 s .c o m number = Integer.valueOf(one.intValue() / two.intValue()); break; case DDIV: number = Double.valueOf(one.doubleValue() / two.doubleValue()); break; case FDIV: number = Float.valueOf(one.floatValue() / two.floatValue()); break; case LDIV: number = Long.valueOf(one.longValue() / two.longValue()); break; default: return null; } return NodeHelper.getInsnNodeFor(number); }