@Test public void testAggregate() { CountAggregate aa = new CountAggregate(); Number num; num = aa.aggregate(null); assertNull(num); num = aa.aggregate(new Number[] {}); assertNull(num); num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0, 0, 0})); assertEquals(3, num.intValue()); num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1, 0})); assertEquals(2, num.intValue()); num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0, 0, 1, 2, 3})); assertEquals(5, num.intValue()); num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0, 0, 0})); assertEquals(3, num.doubleValue(), 0.0); num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1, 1})); assertEquals(2, num.doubleValue(), 0.0); num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0, 0, 1, 4, 5})); assertEquals(5, num.doubleValue(), 0.0); }
private void initSlider(SpinnerNumberModel model) { Number min = ((Number) model.getMinimum()); Number max = ((Number) model.getMaximum()); Number value = ((Number) model.getValue()); Number stepSizeNumber = model.getStepSize(); useWholeNumbers = stepSizeNumber instanceof Integer; if (useWholeNumbers) { slider = new JSlider(min.intValue(), max.intValue(), value.intValue()); slider.setMinorTickSpacing(stepSizeNumber.intValue()); } else { stepSize = stepSizeNumber.doubleValue(); int minimum = (int) Math.round(min.doubleValue() / stepSize); int maximum = (int) Math.round(max.doubleValue() / stepSize); int intValue = (int) Math.round(value.doubleValue() / stepSize); slider = new JSlider(minimum, maximum, intValue); slider.setMinorTickSpacing(stepSizeNumber.intValue()); } Dimension size = slider.getPreferredSize(); size = new Dimension((int) (size.getWidth() * .60), (int) size.getHeight()); slider.setPreferredSize(size); slider.setSnapToTicks(true); slider.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { updateSpinnerState(); } }); }
@Test public void testQuotientAndMultiply() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery<Number> criteria = builder.createQuery(Number.class); criteria.from(Product.class); criteria.select( builder.quot( builder.prod( builder.literal(BigDecimal.valueOf(10.0)), builder.literal(BigDecimal.valueOf(5.0))), BigDecimal.valueOf(2.0))); Number result = em.createQuery(criteria).getSingleResult(); assertEquals(25.0d, result.doubleValue(), 0.1d); criteria.select( builder.prod( builder.quot( builder.literal(BigDecimal.valueOf(10.0)), builder.literal(BigDecimal.valueOf(5.0))), BigDecimal.valueOf(2.0))); result = em.createQuery(criteria).getSingleResult(); assertEquals(4.0d, result.doubleValue(), 0.1d); em.getTransaction().commit(); em.close(); }
static boolean equals(Object o1, Object o2) { if (o1 == o2) return true; if (o1 instanceof JsonObject) { return objectEquals(((JsonObject) o1).map, o2); } if (o1 instanceof Map<?, ?>) { return objectEquals((Map<?, ?>) o1, o2); } if (o1 instanceof JsonArray) { return JsonArray.arrayEquals(((JsonArray) o1).getList(), o2); } if (o1 instanceof List<?>) { return JsonArray.arrayEquals((List<?>) o1, o2); } if (o1 instanceof Number && o2 instanceof Number && o1.getClass() != o2.getClass()) { Number n1 = (Number) o1; Number n2 = (Number) o2; if (o1 instanceof Float || o1 instanceof Double || o2 instanceof Float || o2 instanceof Double) { return n1.doubleValue() == n2.doubleValue(); } else { return n1.longValue() == n2.longValue(); } } return o1.equals(o2); }
/** * Calculates the median for a sublist within a list of values (<code>Number</code> objects). The * entire list will be sorted if the <code>ascending</code< argument is <code>false</code>. * * @param values the values (<code>null</code> not permitted). * @param start the start index. * @param end the end index. * @param copyAndSort a flag that that controls whether the list of values is copied and sorted. * @return The median. */ public static double calculateMedian(List values, int start, int end, boolean copyAndSort) { double result = Double.NaN; if (copyAndSort) { List working = new ArrayList(end - start + 1); for (int i = start; i <= end; i++) { working.add(values.get(i)); } Collections.sort(working); result = calculateMedian(working, false); } else { int count = end - start + 1; if (count > 0) { if (count % 2 == 1) { if (count > 1) { Number value = (Number) values.get(start + (count - 1) / 2); result = value.doubleValue(); } else { Number value = (Number) values.get(start); result = value.doubleValue(); } } else { Number value1 = (Number) values.get(start + count / 2 - 1); Number value2 = (Number) values.get(start + count / 2); result = (value1.doubleValue() + value2.doubleValue()) / 2.0; } } } return result; }
/** * Calculates the median for a list of values (<code>Number</code> objects). If <code>copyAndSort * </code> is <code>false</code>, the list is assumed to be presorted in ascending order by value. * * @param values the values (<code>null</code> permitted). * @param copyAndSort a flag that controls whether the list of values is copied and sorted. * @return The median. */ public static double calculateMedian(List values, boolean copyAndSort) { double result = Double.NaN; if (values != null) { if (copyAndSort) { int itemCount = values.size(); List copy = new ArrayList(itemCount); for (int i = 0; i < itemCount; i++) { copy.add(i, values.get(i)); } Collections.sort(copy); values = copy; } int count = values.size(); if (count > 0) { if (count % 2 == 1) { if (count > 1) { Number value = (Number) values.get((count - 1) / 2); result = value.doubleValue(); } else { Number value = (Number) values.get(0); result = value.doubleValue(); } } else { Number value1 = (Number) values.get(count / 2 - 1); Number value2 = (Number) values.get(count / 2); result = (value1.doubleValue() + value2.doubleValue()) / 2.0; } } } return result; }
@JtwigFunction(name = "divisable by") public boolean isDivisableBy(@Parameter Number value, @Parameter Number dividend) { double value1 = value.doubleValue(); double value2 = dividend.doubleValue(); return value1 % value2 == 0; }
public Number compute(Number d1, Number d2) { double d2Double = d2.doubleValue(); if ((divisionByZeroReturnsNull) && (d2Double == 0)) { return null; } return d1.doubleValue() / d2Double; }
/** * This is a constructor provided to clone Number. Since V is instantiation time and not known * during module creation, a copy is needed. Currently only the following are supported: Double, * Integer, Float, Long, and Short. If you derive your own class from Number then you need to * override getValue to help make a correct copy. * * @param num to clone from * @return value as a correct sub-class (V) object */ @SuppressWarnings("unchecked") public V getValue(Number num) { Number val; switch (type) { case DOUBLE: val = new Double(num.doubleValue()); break; case INTEGER: val = new Integer(num.intValue()); break; case FLOAT: val = new Float(num.floatValue()); break; case LONG: val = new Long(num.longValue()); break; case SHORT: val = new Short(num.shortValue()); break; default: val = new Double(num.doubleValue()); break; } return (V) val; }
/** * Expression may return number value which is not directly compatible with feature type (e.g. * Double when Integer is expected), or EEnumLiteral meta-object when literal instance is expected * * @generated */ public static Object performCast(Object value, EDataType targetType) { if (targetType instanceof EEnum) { if (value instanceof EEnumLiteral) { EEnumLiteral literal = (EEnumLiteral) value; return (literal.getInstance() != null) ? literal.getInstance() : literal; } } if (false == value instanceof Number || targetType == null || targetType.getInstanceClass() == null) { return value; } Class<?> targetClass = targetType.getInstanceClass(); Number num = (Number) value; Class<?> valClass = value.getClass(); Class<?> targetWrapperClass = targetClass; if (targetClass.isPrimitive()) { targetWrapperClass = EcoreUtil.wrapperClassFor(targetClass); } if (valClass.equals(targetWrapperClass)) { return value; } if (Number.class.isAssignableFrom(targetWrapperClass)) { if (targetWrapperClass.equals(Byte.class)) return new Byte(num.byteValue()); if (targetWrapperClass.equals(Integer.class)) return new Integer(num.intValue()); if (targetWrapperClass.equals(Short.class)) return new Short(num.shortValue()); if (targetWrapperClass.equals(Long.class)) return new Long(num.longValue()); if (targetWrapperClass.equals(BigInteger.class)) return BigInteger.valueOf(num.longValue()); if (targetWrapperClass.equals(Float.class)) return new Float(num.floatValue()); if (targetWrapperClass.equals(Double.class)) return new Double(num.doubleValue()); if (targetWrapperClass.equals(BigDecimal.class)) return new BigDecimal(num.doubleValue()); } return value; }
public static MiningModel encodeGradientBoosting( List<DecisionTreeRegressor> regressors, Number initialPrediction, Number learningRate, Schema schema) { List<TreeModel> treeModels = TreeModelUtil.encodeTreeModelSegmentation(regressors, MiningFunction.REGRESSION, schema); Targets targets = new Targets() .addTargets( ModelUtil.createRescaleTarget( schema.getTargetField(), learningRate.doubleValue(), initialPrediction.doubleValue())); MiningModel miningModel = new MiningModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema)) .setSegmentation( MiningModelUtil.createSegmentation( Segmentation.MultipleModelMethod.SUM, treeModels)) .setTargets(targets); return miningModel; }
public static int compare(Number param, Number threshold) throws Throwable { try { int eval = 0; if (threshold instanceof Double) { eval = Double.compare(param.doubleValue(), threshold.doubleValue()); } else if (threshold instanceof Float) { eval = Float.compare(param.floatValue(), threshold.floatValue()); } else if (threshold instanceof Long) { eval = (Long.valueOf(param.longValue())).compareTo(Long.valueOf(threshold.longValue())); } else if (threshold instanceof Integer) { eval = param.intValue() > threshold.intValue() ? 1 : -1; } return eval; } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable e) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); throw e; } }
/** {@inheritDoc} */ @Override protected void updateMinMax(Number min, Number max) { // we always use the double values, because that way the response Object class is // consistent regardless of whether we only have 1 value or many that we min/max // // TODO: would be nice to have subclasses for each type of Number ... breaks backcompat if (computeMin) { // nested if to encourage JIT to optimize aware final var? if (null != min) { double minD = min.doubleValue(); if (null == this.min || minD < this.minD) { // Double for result & cached primitive doulbe to minimize unboxing in future comparisons this.min = this.minD = minD; } } } if (computeMax) { // nested if to encourage JIT to optimize aware final var? if (null != max) { double maxD = max.doubleValue(); if (null == this.max || this.maxD < maxD) { // Double for result & cached primitive doulbe to minimize unboxing in future comparisons this.max = this.maxD = maxD; } } } }
@Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { SpelNodeImpl leftOp = getLeftOperand(); SpelNodeImpl rightOp = getRightOperand(); Object operandOne = leftOp.getValueInternal(state).getValue(); Object operandTwo = rightOp.getValueInternal(state).getValue(); if (operandOne instanceof Number && operandTwo instanceof Number) { Number op1 = (Number) operandOne; Number op2 = (Number) operandTwo; if (op1 instanceof Double || op2 instanceof Double) { return new TypedValue(Math.pow(op1.doubleValue(), op2.doubleValue())); } else if (op1 instanceof Long || op2 instanceof Long) { double d = Math.pow(op1.longValue(), op2.longValue()); return new TypedValue((long) d); } else { double d = Math.pow(op1.longValue(), op2.longValue()); if (d > Integer.MAX_VALUE) { return new TypedValue((long) d); } else { return new TypedValue((int) d); } } } return state.operate(Operation.POWER, operandOne, operandTwo); }
public void addCutoff(Number num, String label) { double lastPoint = 0; if (points.length > 0) { lastPoint = points[points.length - 1]; if (num.doubleValue() <= lastPoint) throw new IllegalArgumentException( "The cutoff you're trying to add (" + num + ") is <= the last cutoff (" + lastPoint + ")"); } if (label == null) { if (points.length == 0) label = "< " + num; else label = "[" + lastPoint + ", " + num + ")"; } double[] temp = new double[points.length + 1]; for (int i = 0; i < points.length; ++i) temp[i] = points[i]; temp[points.length] = num.doubleValue(); points = temp; String[] temp2 = new String[labels.length + 1]; for (int i = 0; i < labels.length; ++i) temp2[i] = labels[i]; temp2[labels.length] = label; labels = temp2; }
/** * Returns the mean of a collection of <code>Number</code> objects. * * @param values the values (<code>null</code> not permitted). * @param includeNullAndNaN a flag that controls whether or not <code>null</code> and <code> * Double.NaN</code> values are included in the calculation (if either is present in the * array, the result is {@link Double#NaN}). * @return The mean. * @since 1.0.3 */ public static double calculateMean(Collection values, boolean includeNullAndNaN) { if (values == null) { throw new IllegalArgumentException("Null 'values' argument."); } int count = 0; double total = 0.0; Iterator iterator = values.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); if (object == null) { if (includeNullAndNaN) { return Double.NaN; } } else { if (object instanceof Number) { Number number = (Number) object; double value = number.doubleValue(); if (Double.isNaN(value)) { if (includeNullAndNaN) { return Double.NaN; } } else { total = total + number.doubleValue(); count = count + 1; } } } } return total / count; }
private static Object toType(Number val, int returnType) { switch (returnType) { case DataTypes.W_DOUBLE: case DataTypes.DOUBLE: return val.doubleValue(); case DataTypes.W_FLOAT: case DataTypes.FLOAT: return val.floatValue(); case DataTypes.INTEGER: case DataTypes.W_INTEGER: return val.intValue(); case DataTypes.W_LONG: case DataTypes.LONG: return val.longValue(); case DataTypes.W_SHORT: case DataTypes.SHORT: return val.shortValue(); case DataTypes.BIG_DECIMAL: return new BigDecimal(val.doubleValue()); case DataTypes.BIG_INTEGER: return BigInteger.valueOf(val.longValue()); case DataTypes.STRING: return val.doubleValue(); } throw new RuntimeException("internal error: " + returnType); }
/** * This method is invoked when the builtin is called in a rule body. * * @param args the array of argument values for the builtin, this is an array of Nodes, some of * which may be Node_RuleVariables. * @param length the length of the argument list, may be less than the length of the args array * for some rule engines * @param context an execution context giving access to other relevant data * @return return true if the buildin predicate is deemed to have succeeded in the current * environment */ public boolean bodyCall(Node[] args, int length, RuleContext context) { checkArgs(length, context); BindingEnvironment env = context.getEnv(); Node n1 = getArg(0, args, context); Node n2 = getArg(1, args, context); if (n1.isLiteral() && n2.isLiteral()) { Object v1 = n1.getLiteralValue(); Object v2 = n2.getLiteralValue(); Node sum = null; if (v1 instanceof Number && v2 instanceof Number) { Number nv1 = (Number) v1; Number nv2 = (Number) v2; if (v1 instanceof Float || v1 instanceof Double || v2 instanceof Float || v2 instanceof Double) { sum = Util.makeDoubleNode(nv1.doubleValue() - nv2.doubleValue()); } else { sum = Util.makeLongNode(nv1.longValue() - nv2.longValue()); } return env.bind(args[2], sum); } } // Doesn't (yet) handle partially bound cases return false; }
private int DomainMin() { double smallest = Double.MAX_VALUE; for (Number d : dates) { if (d.doubleValue() < smallest) smallest = d.doubleValue(); } return (int) (smallest / 86400); }
public Object evaluate() throws EvaluationException { try { Number l = (Number) left().evaluate(); Number r = (Number) right().evaluate(); boolean lIsNonInteger = l instanceof Float || l instanceof Double; boolean rIsNonInteger = r instanceof Float || r instanceof Double; if (lIsNonInteger && rIsNonInteger) value(new Double(l.doubleValue() + r.doubleValue())); else if (lIsNonInteger || rIsNonInteger) { String[] parameters = { Util.getMessage("EvaluationException.plus"), left().value().getClass().getName(), right().value().getClass().getName() }; throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters)); } else { // Addition (+) BigInteger tmpL = (BigInteger) l, tmpR = (BigInteger) r; value(tmpL.add(tmpR)); // daz value (new Long (l.longValue () + r.longValue ())); } } catch (ClassCastException e) { String[] parameters = { Util.getMessage("EvaluationException.plus"), left().value().getClass().getName(), right().value().getClass().getName() }; throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters)); } return value(); } // evaluate
private Number incrValue(int dir) { Number newValue; if ((value instanceof Float) || (value instanceof Double)) { double v = value.doubleValue() + (stepSize.doubleValue() * (double) dir); if (value instanceof Double) { newValue = new Double(v); } else { newValue = new Float(v); } } else { long v = value.longValue() + (stepSize.longValue() * (long) dir); if (value instanceof Long) { newValue = new Long(v); } else if (value instanceof Integer) { newValue = new Integer((int) v); } else if (value instanceof Short) { newValue = new Short((short) v); } else { newValue = new Byte((byte) v); } } if ((maximum != null) && (maximum.compareTo(newValue) < 0)) { return null; } if ((minimum != null) && (minimum.compareTo(newValue) > 0)) { return null; } else { return newValue; } }
/** * What is the min/max/mean/stdev in the collection of aggregates (assuming its over numbers). * * <p>By default NaNs, Nulls and infinity are fully skipped. However, if the relevant parameters * set to false they will be included in the "count" basis and thus influence the mean. * * <p>* */ public static <N extends Number> Stats<N> stats( Aggregates<? extends N> aggregates, boolean ignoreNulls, boolean ignoreNaNs, boolean ignoreInfinity) { // For a single-test std. dev is based on: // http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods long count = 0; long nullCount = 0; long nanCount = 0; long infCount = 0; N min = null; N max = null; double sum = 0; for (N n : aggregates) { if (n == null) { nullCount++; continue; } double v = n.doubleValue(); if (Double.isNaN(v)) { nanCount++; continue; } if (Double.isInfinite(v)) { infCount++; continue; } if (min == null || min.doubleValue() > v) { min = n; } if (max == null || max.doubleValue() < v) { max = n; } sum += v; count++; } final long fullCount = count + (ignoreNulls ? 0 : nullCount) + (ignoreNaNs ? 0 : nanCount) + (ignoreInfinity ? 0 : infCount); final double mean = sum / fullCount; double acc = 0; for (Number n : aggregates) { if (n == null || Double.isNaN(n.doubleValue())) { continue; } acc = Math.pow((n.doubleValue() - mean), 2); } double stdev = Math.sqrt(acc / fullCount); return new Stats<>(min, max, mean, stdev, nullCount, nanCount); }
/** * Compares two {@link KeyedValue} instances and returns an <code>int</code> that indicates the * relative order of the two objects. * * @param o1 object 1. * @param o2 object 2. * @return An int indicating the relative order of the objects. */ @Override public int compare(Object o1, Object o2) { if (o2 == null) { return -1; } if (o1 == null) { return 1; } int result; KeyedValue kv1 = (KeyedValue) o1; KeyedValue kv2 = (KeyedValue) o2; if (this.type == KeyedValueComparatorType.BY_KEY) { if (this.order.equals(SortOrder.ASCENDING)) { result = kv1.getKey().compareTo(kv2.getKey()); } else if (this.order.equals(SortOrder.DESCENDING)) { result = kv2.getKey().compareTo(kv1.getKey()); } else { throw new IllegalArgumentException("Unrecognised sort order."); } } else if (this.type == KeyedValueComparatorType.BY_VALUE) { Number n1 = kv1.getValue(); Number n2 = kv2.getValue(); if (n2 == null) { return -1; } if (n1 == null) { return 1; } double d1 = n1.doubleValue(); double d2 = n2.doubleValue(); if (this.order.equals(SortOrder.ASCENDING)) { if (d1 > d2) { result = 1; } else if (d1 < d2) { result = -1; } else { result = 0; } } else if (this.order.equals(SortOrder.DESCENDING)) { if (d1 > d2) { result = -1; } else if (d1 < d2) { result = 1; } else { result = 0; } } else { throw new IllegalArgumentException("Unrecognised sort order."); } } else { throw new IllegalArgumentException("Unrecognised type."); } return result; }
/** * Helper function to compare Number objects. This is needed because Java doesn't allow comparing, * for example, Integer objects to Double objects. */ private int compareValues(Number probe, Number target) { double d1 = probe.doubleValue(); double d2 = target.doubleValue(); if (d1 < d2) return -1; else if (d1 > d2) return 1; else return 0; }
private Double FindMinimum() { Double smallest = 1000.0; for (Number d : weights) { if (d.doubleValue() < smallest.doubleValue()) smallest = d.doubleValue(); } Double bit = smallest % 1; return smallest - bit; }
@Override public ComparisonResult apply(Number actual, Number expected) { if (actual == expected) return new ComparisonResult(actual, expected, this, true); if (actual == null || expected == null) return new ComparisonResult(actual, expected, this, false); boolean equals = DoubleMath.equals(actual.doubleValue(), expected.doubleValue()); return new ComparisonResult(actual, expected, this, equals); }
private Double FindMaximum() { Double greatest = 0.0; for (Number d : weights) { if (d.doubleValue() > greatest) greatest = d.doubleValue(); } Double bit = 1 - greatest % 1; return greatest + bit; }
@Override public Number divide(Number n) { if (n.doubleValue() == 0.0) throw new LispException(Symbol.DIVZEROCONDITION, "division by zero"); double result = val / n.doubleValue(); if (isIntRepresentable(result)) return IntNum.fromLong((long) result); return new FloatNum(result); }
/** * Creates a {@link RenderedImage} representing the results of an imaging operation for a given * {@link ParameterBlock} and {@link RenderingHints}. */ @Override public RenderedImage create(final ParameterBlock param, final RenderingHints hints) { final RenderedImage image = (RenderedImage) param.getSource(0); final Number srcVal = (Number) param.getObjectParameter(0); final Number destVal = (Number) param.getObjectParameter(1); return new RecodeRaster(image, srcVal.doubleValue(), destVal.doubleValue(), hints); }
private int DomainMax() { double greatest = 0.0; for (Number d : dates) { if (d.doubleValue() > greatest) greatest = d.doubleValue(); } return (int) (greatest / 86400); }