List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:net.sourceforge.processdash.ui.web.reports.RadarChart.java
private void maybeScaleDataAxes() { for (int i = 0; i < data.numCols(); i++) { int n = i + 1; String target = getParameter("t" + n); if (!StringUtils.hasValue(target)) continue; double targetVal = 0; try {// w w w. j a v a2 s. c om targetVal = FormatUtil.parseNumber(target); } catch (Exception e) { SaveableData val = getDataRepository().getInheritableValue(getPrefix(), target); if (val != null) { SimpleData sVal = val.getSimpleValue(); if (sVal instanceof NumberData) targetVal = ((NumberData) sVal).getDouble(); } } if (targetVal == 0) continue; boolean reverse = parameters.containsKey("r" + n); SimpleData d = data.getData(1, n); if (d instanceof NumberData) { NumberData num = (NumberData) d; double val = num.getDouble(); if (Double.isInfinite(val) || Double.isNaN(val)) val = 1.0; else if (reverse) val = 2.0 / (1.0 + (val / targetVal)); else val = val / targetVal; data.setData(1, n, new DoubleData(val)); } } }
From source file:org.esa.snap.core.datamodel.Stx.java
/** * Constructor. Avoid using it directly. instead, use the {@link StxFactory} since the constructor may change in the future. * * @param minimum the minimum value, if it is {@link Double#NaN} the minimum is taken from the {@code histogram} * @param maximum the maximum value, if it is {@link Double#NaN} the maximum is taken from the {@code histogram} * @param mean the mean value, if it is {@link Double#NaN} the mean is taken from the {@code histogram} * @param standardDeviation the value of the standard deviation, if it is {@link Double#NaN} it is taken from the {@code histogram} * @param coeffOfVariation the Coefficient of Variation * @param enl Equivalent number of looks * @param logHistogram {@code true} if the histogram has been computed on logarithms, see {@link #getHistogram()} * @param intHistogram {@code true} if the histogram has been computed from integer samples, see {@link #getHistogram()} * @param histogram the histogram * @param resolutionLevel the resolution level this {@code Stx} is for *///from ww w .ja v a 2 s . co m public Stx(double minimum, double maximum, double mean, double standardDeviation, double coeffOfVariation, double enl, boolean logHistogram, boolean intHistogram, Histogram histogram, int resolutionLevel) { Assert.argument(!Double.isNaN(minimum), "minimum must not be NaN"); Assert.argument(!Double.isInfinite(minimum), "minimum must not be infinity"); Assert.argument(!Double.isNaN(maximum), "maximum must not be NaN"); Assert.argument(!Double.isInfinite(maximum), "minimum must not be infinity"); Assert.argument(resolutionLevel >= 0, "resolutionLevel"); // todo - this is still a lot of behaviour, move all computations to StxFactory (nf) this.sampleCount = StxFactory.computeSum(histogram.getBins(0)); this.minimum = minimum; this.maximum = maximum; this.histogramScaling = getHistogramScaling(logHistogram); if (minimum == maximum) { this.mean = minimum; this.standardDeviation = 0.0; this.median = maximum; } else { this.mean = Double.isNaN(mean) ? histogramScaling.scaleInverse(histogram.getMean()[0]) : mean; this.standardDeviation = Double.isNaN(standardDeviation) ? histogramScaling.scaleInverse(histogram.getStandardDeviation()[0]) : standardDeviation; this.median = histogramScaling.scaleInverse(StxFactory.computeMedian(histogram, this.sampleCount)); } this.logHistogram = logHistogram; this.intHistogram = intHistogram; this.histogram = histogram; this.resolutionLevel = resolutionLevel; this.coefficientOfVariation = coeffOfVariation; this.enl = enl; }
From source file:org.hyperic.hq.ui.taglib.display.MetricDecorator.java
public String decorate(Object obj) throws Exception { try {//w w w. j a v a 2 s. c om // if the metric value is empty, converting to a Double // will give a value of 0.0. this makes it impossible for // us to distinguish further down the line whether the // metric was actually collected with a value of 0.0 or // whether it was not collected at all. therefore, we'll // let m be null if the metric was not collected, and // we'll check for null later when handling the not-avail // case. // PR: 7588 Double m = null; if (obj != null) { String mval = obj.toString(); if (mval != null && !mval.equals("")) { m = new Double(mval); } } String u = getUnit(); String dk = getDefaultKey(); Locale l = TagUtils.getInstance().getUserLocale(context, locale); StringBuffer buf = new StringBuffer(); if ((m == null || Double.isNaN(m.doubleValue()) || Double.isInfinite(m.doubleValue())) && dk != null) { buf.append(TagUtils.getInstance().message(context, bundle, l.toString(), dk)); } else if (u.equals("ms")) { // we don't care about scaling and such. we just want // to show every metric in seconds with millisecond // resolution String formatted = UnitsFormat.format( new UnitNumber(m.doubleValue(), UnitsConstants.UNIT_DURATION, UnitsConstants.SCALE_MILLI)) .toString(); buf.append(formatted); } else { FormattedNumber f = UnitsConvert.convert(m.doubleValue(), u, l); buf.append(f.getValue()); if (f.getTag() != null && f.getTag().length() > 0) { buf.append(" ").append(f.getTag()); } } return buf.toString(); } catch (NumberFormatException npe) { log.error(npe); throw new JspTagException(npe); } catch (Exception e) { log.error(e); throw new JspException(e); } }
From source file:geogebra.kernel.AlgoRootNewton.java
final double calcRoot(Function fun, double start) { double root = Double.NaN; if (rootFinderBrent == null) rootFinderBrent = new BrentSolver(Kernel.STANDARD_PRECISION); // try Brent method with borders close to start value try {//from w ww. ja va 2s .co m double step = (kernel.getXmax() - kernel.getXmin()) / 10; root = rootFinderBrent.solve(MAX_ITERATIONS, new RealRootAdapter(fun), start - step, start + step, start); if (checkRoot(fun, root)) { //System.out.println("1. Brent worked: " + root); return root; } } catch (Exception e) { root = Double.NaN; } // try Brent method on valid interval around start double[] borders = getDomain(fun, start); try { root = rootFinderBrent.solve(MAX_ITERATIONS, new RealRootAdapter(fun), borders[0], borders[1], start); if (checkRoot(fun, root)) { //System.out.println("2. Brent worked: " + root); return root; } } catch (Exception e) { root = Double.NaN; } // try Newton's method RealRootDerivFunction derivFun = fun.getRealRootDerivFunction(); if (derivFun != null) { // check if fun(start) is defined double eval = fun.evaluate(start); if (Double.isNaN(eval) || Double.isInfinite(eval)) { // shift left border slightly right borders[0] = 0.9 * borders[0] + 0.1 * borders[1]; start = (borders[0] + borders[1]) / 2; } if (rootFinderNewton == null) { rootFinderNewton = new NewtonSolver(); } try { root = rootFinderNewton.solve(MAX_ITERATIONS, new RealRootDerivAdapter(derivFun), borders[0], borders[1], start); if (checkRoot(fun, root)) { //System.out.println("Newton worked: " + root); return root; } } catch (Exception e) { root = Double.NaN; } } // neither Brent nor Newton worked return Double.NaN; }
From source file:edu.umn.msi.tropix.proteomics.itraqquantitation.impl.Variance.java
static double[][] createVarianceMatrix(final List<ITraqLabel> labels, final Map<ITraqLabel, double[]> intensities, final double[] ds, final int binSize) { final int n = intensities.values().iterator().next().length; final double[] reference = new double[n]; for (int i = 0; i < n; i++) { double intensitiesProduct = 1.0d; for (final ITraqLabel label : labels) { final double intensity = intensities.get(label)[i]; intensitiesProduct *= intensity; }/*from w w w .j a va 2 s. c o m*/ reference[i] = MathUtils.log(2.0, intensitiesProduct); } // final double[] sortedReference = Arrays.copyOf(reference, reference.length); final double[] sortedReference = new double[reference.length]; for (int i = 0; i < reference.length; i++) { sortedReference[i] = reference[i]; } Arrays.sort(sortedReference); final List<ITraqRatio> ratios = ITraqLabels.buildRatios(labels); final int numRatios = ratios.size(); final int numRows = numRatios * n; // Precompute ratios final double[] actualRatios = new double[numRatios]; final double[][] numerators = new double[numRatios][]; final double[][] denominators = new double[numRatios][]; for (int ratioIndex = 0; ratioIndex < numRatios; ratioIndex++) { final ITraqRatio ratio = ratios.get(ratioIndex); final int numeratorIndex = labels.indexOf(ratio.getNumerator()); final int denominatorIndex = labels.indexOf(ratio.getDenominator()); numerators[ratioIndex] = intensities.get(ratio.getNumerator()); denominators[ratioIndex] = intensities.get(ratio.getDenominator()); actualRatios[ratioIndex] = MathUtils.log(2.0, ds[numeratorIndex] / ds[denominatorIndex]); } final double[][] samplePoints = new double[numRows][2]; for (int sortedReferenceIndex = 0; sortedReferenceIndex < n; sortedReferenceIndex++) { final double referenceValue = sortedReference[sortedReferenceIndex]; final int referenceIndex = indexOf(referenceValue, reference); final int rowOffset = sortedReferenceIndex * numRatios; for (int ratioIndex = 0; ratioIndex < numRatios; ratioIndex++) { final double actualRatio = actualRatios[ratioIndex]; final double estimatedRatio = MathUtils.log(2.0, numerators[ratioIndex][referenceIndex] / denominators[ratioIndex][referenceIndex]); final double diff = (estimatedRatio - actualRatio); samplePoints[rowOffset + ratioIndex][0] = referenceValue; samplePoints[rowOffset + ratioIndex][1] = diff * diff; } } final int numBins = numRows / binSize; final double[][] matrixXV = new double[numBins][2]; double maxV = Double.MIN_VALUE; double sumX = 0.0, sumV = 0.0; int curBin = 0; for (int i = 0; i < numRows; i++) { sumX += samplePoints[i][0]; sumV += samplePoints[i][1]; if ((i + 1) % binSize == 0) { final double x = sumX / binSize; final double v = sumV / binSize; final double binWeight = 1 / v; if (!Double.isInfinite(binWeight)) { maxV = Math.max(binWeight, maxV); } matrixXV[curBin][0] = x; matrixXV[curBin][1] = binWeight; curBin++; sumX = 0.0; sumV = 0.0; } } for (int i = 0; i < numBins; i++) { if (Double.isInfinite(matrixXV[i][1])) { matrixXV[i][1] = maxV; } } for (int i = 0; i < numBins - 1; i++) { matrixXV[i][0] = (matrixXV[i][0] + matrixXV[i + 1][0]) / 2.0; } return matrixXV; }
From source file:org.renjin.parser.NumericLiterals.java
public static String toString(double value) { if (Double.isNaN(value)) { return "NaN"; }//from w ww .ja v a 2 s .c o m if (Double.isInfinite(value)) { if (value < 0) { return "-Inf"; } else { return "Inf"; } } // TODO: the original R implementation formats numbers based on options, // this is just a quick hack if (value > 100000) { return Double.toString(value); } return REAL_FORMAT.format(value); }
From source file:org.rhq.enterprise.gui.legacy.taglib.display.MetricDecorator.java
@Override public String decorate(Object obj) throws Exception { try {// ww w .j a va 2 s. c o m // if the metric value is empty, converting to a Double // will give a value of 0.0. this makes it impossible for // us to distinguish further down the line whether the // metric was actually collected with a value of 0.0 or // whether it was not collected at all. therefore, we'll // let m be null if the metric was not collected, and // we'll check for null later when handling the not-avail // case. // PR: 7588 Double m = null; if (obj != null) { String mval = (String) evalAttr("metric", obj.toString(), String.class); if ((mval != null) && !mval.equals("")) { m = new Double(mval); } } Locale l = RequestUtils.retrieveUserLocale(context, locale); StringBuffer buf = new StringBuffer(); if (((m == null) || Double.isNaN(m.doubleValue()) || Double.isInfinite(m.doubleValue())) && (defaultKey != null)) { buf.append(RequestUtils.message(context, bundle, l.toString(), defaultKey)); } else if (unit.equals("ms")) { // we don't care about scaling and such. we just want // to show every metric in seconds with millisecond // resolution String formatted = UnitsFormat.format( new UnitNumber(m.doubleValue(), UnitsConstants.UNIT_DURATION, ScaleConstants.SCALE_MILLI)) .toString(); buf.append(formatted); } else { MeasurementUnits targetUnits = MeasurementUnits.valueOf(unit); Double dataValue = m.doubleValue(); String formatted = MeasurementConverter.format(dataValue, targetUnits, true); buf.append(formatted); } return buf.toString(); } catch (JspException je) { log.error(je); throw je; } catch (Exception e) { log.error(e); throw new JspException(e); } }
From source file:TrainLogistic.java
static void mainToOutput(String[] args, PrintWriter output) throws Exception { if (parseArgs(args)) { double logPEstimate = 0; int samples = 0; /*read files in dir of inputFile*/ int fi = 0;//file ID File file = new File(inputFile); String[] fns = file.list(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith(".svm")) { return true; } else { return false; }// w w w .j av a2 s . co m } }); String[] ss = new String[lmp.getNumFeatures() + 1]; String[] iv = new String[2]; OnlineLogisticRegression lr = lmp.createRegression(); while (fi < fns.length) { for (int pass = 0; pass < passes; pass++) { BufferedReader in = open(inputFile + fns[fi]); System.out.println(pass + 1); try { // read variable names String line = in.readLine(); int lineCount = 1; while (line != null) { // for each new line, get target and predictors Vector input = new RandomAccessSparseVector(lmp.getNumFeatures()); ss = line.split(" "); int targetValue; if (ss[0].startsWith("+")) targetValue = 1; else targetValue = 0; int k = 1; while (k < ss.length) { iv = ss[k].split(":"); input.setQuick(Integer.valueOf(iv[0]) - 1, Double.valueOf(iv[1])); //System.out.printf("%d-----%d:%.4f====%d\n", k,Integer.valueOf(iv[0])-1,Double.valueOf(iv[1]),lineCount); k++; } input.setQuick(lmp.getNumFeatures() - 1, 1); // check performance while this is still news double logP = lr.logLikelihood(targetValue, input); if (!Double.isInfinite(logP)) { if (samples < 20) { logPEstimate = (samples * logPEstimate + logP) / (samples + 1); } else { logPEstimate = 0.95 * logPEstimate + 0.05 * logP; } samples++; } double p = lr.classifyScalar(input); if (scores) { output.printf(Locale.ENGLISH, "%10d %2d %10.2f %2.4f %10.4f %10.4f\n", samples, targetValue, lr.currentLearningRate(), p, logP, logPEstimate); } // now update model lr.train(targetValue, input); if ((lineCount) % 1000 == 0) System.out.printf("%d\t", lineCount); line = in.readLine(); lineCount++; } } finally { Closeables.closeQuietly(in); } System.out.println(); } fi++; } FileOutputStream modelOutput = new FileOutputStream(outputFile); try { saveTo(modelOutput, lr); } finally { Closeables.closeQuietly(modelOutput); } /* output.printf(Locale.ENGLISH, "%d\n", lmp.getNumFeatures()); output.printf(Locale.ENGLISH, "%s ~ ", lmp.getTargetVariable()); String sep = ""; for (String v : csv.getTraceDictionary().keySet()) { double weight = predictorWeight(lr, 0, csv, v); if (weight != 0) { output.printf(Locale.ENGLISH, "%s%.3f*%s", sep, weight, v); sep = " + "; } } output.printf("\n"); model = lr; for (int row = 0; row < lr.getBeta().numRows(); row++) { for (String key : csv.getTraceDictionary().keySet()) { double weight = predictorWeight(lr, row, csv, key); if (weight != 0) { output.printf(Locale.ENGLISH, "%20s %.5f\n", key, weight); } } for (int column = 0; column < lr.getBeta().numCols(); column++) { output.printf(Locale.ENGLISH, "%15.9f ", lr.getBeta().get(row, column)); } output.println(); }*/ } }
From source file:com.opengamma.analytics.math.interpolation.LinearInterpolator.java
@Override public PiecewisePolynomialResult interpolate(final double[] xValues, final double[][] yValuesMatrix) { ArgumentChecker.notNull(xValues, "xValues"); ArgumentChecker.notNull(yValuesMatrix, "yValuesMatrix"); ArgumentChecker.isTrue(xValues.length == yValuesMatrix[0].length, "(xValues length = yValuesMatrix's row vector length)"); ArgumentChecker.isTrue(xValues.length > 1, "Data points should be more than 1"); final int nDataPts = xValues.length; final int dim = yValuesMatrix.length; for (int i = 0; i < nDataPts; ++i) { ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN"); ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity"); for (int j = 0; j < dim; ++j) { ArgumentChecker.isFalse(Double.isNaN(yValuesMatrix[j][i]), "yValuesMatrix containing NaN"); ArgumentChecker.isFalse(Double.isInfinite(yValuesMatrix[j][i]), "yValuesMatrix containing Infinity"); }/*from w w w .j a v a 2 s . c o m*/ } for (int k = 0; k < dim; ++k) { for (int i = 0; i < nDataPts; ++i) { for (int j = i + 1; j < nDataPts; ++j) { ArgumentChecker.isFalse(xValues[i] == xValues[j], "xValues should be distinct"); } } } double[] xValuesSrt = new double[nDataPts]; DoubleMatrix2D[] coefMatrix = new DoubleMatrix2D[dim]; for (int i = 0; i < dim; ++i) { xValuesSrt = Arrays.copyOf(xValues, nDataPts); double[] yValuesSrt = Arrays.copyOf(yValuesMatrix[i], nDataPts); ParallelArrayBinarySort.parallelBinarySort(xValuesSrt, yValuesSrt); coefMatrix[i] = solve(xValuesSrt, yValuesSrt); for (int k = 0; k < xValuesSrt.length - 1; ++k) { double ref = 0.; final double interval = xValuesSrt[k + 1] - xValuesSrt[k]; for (int j = 0; j < 2; ++j) { ref += coefMatrix[i].getData()[k][j] * Math.pow(interval, 1 - j); ArgumentChecker.isFalse(Double.isNaN(coefMatrix[i].getData()[k][j]), "Too large input"); ArgumentChecker.isFalse(Double.isInfinite(coefMatrix[i].getData()[k][j]), "Too large input"); } final double bound = Math.max(Math.abs(ref) + Math.abs(yValuesSrt[k + 1]), 1.e-1); ArgumentChecker.isTrue(Math.abs(ref - yValuesSrt[k + 1]) < ERROR * bound, "Input is too large/small or data points are too close"); } } final int nIntervals = coefMatrix[0].getNumberOfRows(); final int nCoefs = coefMatrix[0].getNumberOfColumns(); double[][] resMatrix = new double[dim * nIntervals][nCoefs]; for (int i = 0; i < nIntervals; ++i) { for (int j = 0; j < dim; ++j) { resMatrix[dim * i + j] = coefMatrix[j].getRowVector(i).getData(); } } return new PiecewisePolynomialResult(new DoubleMatrix1D(xValuesSrt), new DoubleMatrix2D(resMatrix), nCoefs, dim); }
From source file:edu.cmu.tetrad.data.GeneralAndersonDarlingTest.java
private void runTest() { int n = data.size(); double h = 0.0; int numSummed = 0; for (int i = 1; i <= n; i++) { double x1 = data.get(i - 1); double a1 = Math.log(dist.cumulativeProbability(x1)); double x2 = data.get(n + 1 - i - 1); double a2 = Math.log(1.0 - dist.cumulativeProbability(x2)); double k = (2 * i - 1) * (a1 + a2); if (!(Double.isNaN(a1) || Double.isNaN(a2) || Double.isInfinite(a1) || Double.isInfinite(a2))) { h += k;/*from w w w .j av a 2 s .c om*/ numSummed++; } } double a = -n - (1.0 / numSummed) * h; double aa = (1 + 0.75 / numSummed + 2.25 / Math.pow(numSummed, 2)) * a; double p; if (aa < 0.2) { p = 1 - Math.exp(-13.436 + 101.14 * aa - 223.73 * aa * aa); } else if (aa < 0.34) { p = 1 - Math.exp(-8.318 + 42.796 * aa - 59.938 * aa * aa); } else if (aa < 0.6) { p = Math.exp(0.9177 - 4.279 * aa - 1.38 * aa * aa); } else { p = Math.exp(1.2937 - 5.709 * aa + 0.0186 * aa * aa); } this.aSquared = a; this.aSquaredStar = aa; this.p = p; }