List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:geogebra.kernel.cas.AlgoIntegralDefinite.java
protected final void compute() { if (!f.isDefined() || !ageo.isDefined() || !bgeo.isDefined()) { n.setUndefined();/*from www . j a v a 2 s.c o m*/ return; } // check for equal bounds double lowerLimit = a.getDouble(); double upperLimit = b.getDouble(); if (Kernel.isEqual(lowerLimit, upperLimit)) { n.setValue(0); return; } // check if f(a) and f(b) are defined double fa = f.evaluate(lowerLimit); double fb = f.evaluate(upperLimit); if (Double.isNaN(fa) || Double.isInfinite(fa) || Double.isNaN(fb) || Double.isInfinite(fb)) { n.setUndefined(); return; } // return if it should not be evaluated (i.e. is shade-only) if (evaluateOnly()) { n.setValue(Double.NaN); return; } /* * Try to use symbolic integral * * We only do this for functions that do NOT include divisions by their variable. * Otherwise there might be problems like: * Integral[ 1/x, -2, -1 ] would be undefined (log(-1) - log(-2)) * Integral[ 1/x^2, -1, 1 ] would be defined (-2) */ if (symbIntegral != null && symbIntegral.isDefined() && !f.includesDivisionByVar()) { double val = symbIntegral.evaluate(upperLimit) - symbIntegral.evaluate(lowerLimit); n.setValue(val); if (n.isDefined()) return; } // numerical integration // max_error = ACCURACY; // current maximum error //maxstep = 0; double integral = numericIntegration(f, lowerLimit, upperLimit); n.setValue(integral); /* Application.debug("***\nsteps: " + maxstep); Application.debug("max_error: " + max_error); */ }
From source file:etomica.potential.P2HSDipole.java
public double virial(IMoleculeList atoms) { gradient(atoms);//from w w w. j a v a 2 s . c o m IMolecule molecule1 = atoms.getMolecule(0); IMolecule molecule2 = atoms.getMolecule(1); IAtomList atomList1 = molecule1.getChildList(); IAtomList atomList2 = molecule2.getChildList(); IAtomOriented atom1 = (IAtomOriented) atomList1.getAtom(0); IAtomOriented atom2 = (IAtomOriented) atomList2.getAtom(0); // LJ contributation dr.Ev1Mv2(atom2.getPosition(), atom1.getPosition()); boundary.nearestImage(dr); double v = gradient[1].dot(dr); if (Double.isInfinite(v)) { throw new RuntimeException("oops " + v); } return gradient[1].dot(dr); }
From source file:edu.cornell.med.icb.goby.R.TestFisherExact.java
/** * Fisher Tea Tasting example. A British woman claimed to be able to distinguish * whether milk or tea was added to the cup first. To test, she was given 8 cups of * tea, in four of which milk was added first. The null hypothesis is that there is * no association between the true order of pouring and the women's guess, the * alternative that there is a positive association (that the odds ratio * is greater than 1).//from w w w. j av a2 s.co m */ @Test public void agrestiTeaTasting() { final int[] inputTable = { /* Truth */ /* Guess Milk Tea */ /* Milk */ 3, 1, /* Tea */ 1, 3 }; final FisherExact.Result result = FisherExact.fexact(inputTable, 2, 2, FisherExact.AlternativeHypothesis.greater); assertEquals("pValue does not match", 0.24285714285714288, result.getPValue(), EPSILON); assertEquals("Lower confidence interval does not match", 0.313569264110218, result.getConfidenceInterval()[0], EPSILON); assertTrue("Upper confidence interval should be infinite", Double.isInfinite(result.getConfidenceInterval()[1])); assertEquals("Estimate does not match", 6.408308867005793, result.getEstimate(), EPSILON); assertEquals("Odds ratio does not match", 1.0, result.getOddsRatio(), EPSILON); assertEquals("Wrong Hypothesis for result", FisherExact.AlternativeHypothesis.greater, result.getAlternativeHypothesis()); }
From source file:edu.duke.cs.osprey.voxq.QuadraticQFunction.java
public QuadraticQFunction(MoleculeModifierAndScorer mms, int dof, double origVal) { //specify voxel/obj fcn, DOF being sampled (indexed in mms), and starting value of dof //start simple: convex quadratic thru origVal and edges //if too much autocorr or rejection will refine DoubleMatrix1D constr[] = mms.getConstraints(); xLo = constr[0].get(dof);// ww w .ja va2s .co m xHi = constr[1].get(dof); if (xHi < xLo + 1e-14) throw new RuntimeException("ERROR: Trying to sample a rigid DOF!"); //constant factor, i.e. energy offset, doesn't matter double origValE = mms.getValForDOF(dof, origVal); double xLoE = mms.getValForDOF(dof, xLo); double xHiE = mms.getValForDOF(dof, xHi); //Choose x1 and x3 to roughly bracket the region from which it is useful to sample //(they'll be voxel edges unless need to move in to avoid clashes) double x1 = chooseReasonableOuterPt(origVal, origValE, xLo, xLoE, mms, dof); double x3 = chooseReasonableOuterPt(origVal, origValE, xHi, xHiE, mms, dof); //choose a point in the middle to build a quadratic (origVal unless too close to one of the edges, //in which case move 10% away from the edge) double x2 = Math.max(origVal, 0.9 * x1 + 0.1 * x3); x2 = Math.min(x2, 0.1 * x1 + 0.9 * x3); double E1 = getEnergyIfNeeded(x1, mms, dof, xLo, xLoE); double E3 = getEnergyIfNeeded(x3, mms, dof, xHi, xHiE); double E2 = getEnergyIfNeeded(x2, mms, dof, origVal, origValE); double slope = (E3 - E1) / (x3 - x1); if (E2 - E1 < slope * (x2 - x1)) {//middle point lies below line between outer points //build quadratic boolean success = setupQuadratic(x1, x2, x3, E1, E2, E3); if ((a != 0 && (!erfcInvNumericsOK())) || (!success)) { //quadratic bad numerically. First condition is for erfc numerics, second for normalization constant setupLinear(x1, x3, E1, E3); } } else setupLinear(x1, x3, E1, E3); for (double q : new double[] { a, b, c }) if (Double.isInfinite(q) || Double.isNaN(q)) throw new RuntimeException("ERROR: Infinite or NaN coefficient in sampling prior"); }
From source file:org.nd4j.linalg.api.rng.distribution.BaseDistribution.java
/** * {@inheritDoc}/*from ww w . j a v a2s . c o m*/ * <p/> * The default implementation returns * <ul> * <li>{@link #getSupportLowerBound()} for {@code p = 0},</li> * <li>{@link #getSupportUpperBound()} for {@code p = 1}.</li> * </ul> */ @Override public double inverseCumulativeProbability(final double p) throws OutOfRangeException { /* * IMPLEMENTATION NOTES * -------------------- * Where applicable, use is made of the one-sided Chebyshev inequality * to bracket the root. This inequality states that * P(X - mu >= k * sig) <= 1 / (1 + k^2), * mu: mean, sig: standard deviation. Equivalently * 1 - P(X < mu + k * sig) <= 1 / (1 + k^2), * F(mu + k * sig) >= k^2 / (1 + k^2). * * For k = sqrt(p / (1 - p)), we find * F(mu + k * sig) >= p, * and (mu + k * sig) is an upper-bound for the root. * * Then, introducing Y = -X, mean(Y) = -mu, sd(Y) = sig, and * P(Y >= -mu + k * sig) <= 1 / (1 + k^2), * P(-X >= -mu + k * sig) <= 1 / (1 + k^2), * P(X <= mu - k * sig) <= 1 / (1 + k^2), * F(mu - k * sig) <= 1 / (1 + k^2). * * For k = sqrt((1 - p) / p), we find * F(mu - k * sig) <= p, * and (mu - k * sig) is a lower-bound for the root. * * In cases where the Chebyshev inequality does not apply, geometric * progressions 1, 2, 4, ... and -1, -2, -4, ... are used to bracket * the root. */ if (p < 0.0 || p > 1.0) { throw new OutOfRangeException(p, 0, 1); } double lowerBound = getSupportLowerBound(); if (p == 0.0) { return lowerBound; } double upperBound = getSupportUpperBound(); if (p == 1.0) { return upperBound; } final double mu = getNumericalMean(); final double sig = FastMath.sqrt(getNumericalVariance()); final boolean chebyshevApplies; chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) || Double.isInfinite(sig) || Double.isNaN(sig)); if (lowerBound == Double.NEGATIVE_INFINITY) { if (chebyshevApplies) { lowerBound = mu - sig * FastMath.sqrt((1. - p) / p); } else { lowerBound = -1.0; while (cumulativeProbability(lowerBound) >= p) { lowerBound *= 2.0; } } } if (upperBound == Double.POSITIVE_INFINITY) { if (chebyshevApplies) { upperBound = mu + sig * FastMath.sqrt(p / (1. - p)); } else { upperBound = 1.0; while (cumulativeProbability(upperBound) < p) { upperBound *= 2.0; } } } final UnivariateFunction toSolve = new UnivariateFunction() { public double value(final double x) { return cumulativeProbability(x) - p; } }; double x = UnivariateSolverUtils.solve(toSolve, lowerBound, upperBound, getSolverAbsoluteAccuracy()); if (!isSupportConnected()) { /* Test for plateau. */ final double dx = getSolverAbsoluteAccuracy(); if (x - dx >= getSupportLowerBound()) { double px = cumulativeProbability(x); if (cumulativeProbability(x - dx) == px) { upperBound = x; while (upperBound - lowerBound > dx) { final double midPoint = 0.5 * (lowerBound + upperBound); if (cumulativeProbability(midPoint) < px) { lowerBound = midPoint; } else { upperBound = midPoint; } } return upperBound; } } } return x; }
From source file:mase.spec.HybridStat.java
private void printMatrix(double[][] m, EvolutionState state) { DecimalFormat df = new DecimalFormat("000.000"); try {//from ww w. j ava2s . c om StringBuilder sb = new StringBuilder(); int rows = m.length; int columns = m[0].length; for (int i = 0; i < rows; i++) { sb.append("| "); for (int j = 0; j < columns; j++) { sb.append(Double.isInfinite(m[i][j]) ? " \u221E " : Double.isNaN(m[i][j]) ? " NaN " : df.format(m[i][j])).append(" "); } sb.append("|\n"); } state.output.message(sb.toString()); } catch (Exception e) { state.output.message("Matrix is empty!!"); } }
From source file:lirmm.inria.fr.math.TestUtils.java
/** * Verifies that the relative error in actual vs. expected is less than or * equal to relativeError. If expected is infinite or NaN, actual must be * the same (NaN or infinity of the same sign). * * @param msg message to return with failure * @param expected expected value//from w ww . j av a 2 s .co m * @param actual observed value * @param relativeError maximum allowable relative error */ public static void assertRelativelyEquals(String msg, double expected, double actual, double relativeError) { if (Double.isNaN(expected)) { Assert.assertTrue(msg, Double.isNaN(actual)); } else if (Double.isNaN(actual)) { Assert.assertTrue(msg, Double.isNaN(expected)); } else if (Double.isInfinite(actual) || Double.isInfinite(expected)) { Assert.assertEquals(expected, actual, relativeError); } else if (expected == 0.0) { Assert.assertEquals(msg, actual, expected, relativeError); } else { double absError = FastMath.abs(expected) * relativeError; Assert.assertEquals(msg, expected, actual, absError); } }
From source file:playground.johannes.socialnetworks.snowball2.analysis.DegreeGrowth.java
private void dump(Sampler<?, ?, ?> sampler) { DescriptiveStatistics stats = ObservedDegree.getInstance() .statistics(sampler.getSampledGraph().getVertices()); if (prevStats != null) { TDoubleDoubleHashMap hist = Histogram.createHistogram(stats, discretizer, false); TDoubleDoubleHashMap prevHist = Histogram.createHistogram(prevStats, discretizer, false); TDoubleDoubleHashMap growth = new TDoubleDoubleHashMap(); TDoubleDoubleIterator it = hist.iterator(); for (int i = 0; i < hist.size(); i++) { it.advance();// w w w. j av a 2 s. c o m double g = it.value() / prevHist.get(it.key()); if (Double.isInfinite(g)) g = 0.0; // System.out.println(String.format("%1$s - %2$s", it.key(), // g)); growth.put(it.key(), g); } // growthTable.put(sampler.getNumSampledVertices(), growth); growthTable.put(sampler.getIteration() - 1, growth); // File file = new File(String.format("%1$s/vertex.%2$s/", output, sampler.getNumSampledVertices())); // file.mkdirs(); // // try { // TXTWriter.writeMap(growth, "k", "growth", String.format("%1$s/k_growth.txt", file.getAbsolutePath())); // TXTWriter.writeMap(hist, "k", "growth", String.format("%1$s/k_hist.txt", file.getAbsolutePath())); // TXTWriter.writeMap(prevHist, "k", "growth",String.format("%1$s/k_prevHist.txt", file.getAbsolutePath())); // // } catch (IOException e) { // e.printStackTrace(); // } } prevStats = stats; }
From source file:gedi.util.MathUtils.java
public static double saveMin(double a, double b) { if (Double.isNaN(a)) return b; if (Double.isNaN(b)) return a; if (Double.isInfinite(a)) return b; if (Double.isInfinite(b)) return a; return Math.min(a, b); }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.SimpleStatistics.java
@Override public void run(CommandLine commandLine) throws Exception { String mode = null;//from www . j av a 2s. co m PrintStream out = null; List<double[][]> entries = new ArrayList<double[][]>(); SummaryStatistics statistics = new SummaryStatistics(); OptionCompleter completer = new OptionCompleter("minimum", "maximum", "average", "stdev", "count"); //load data from all input files for (String filename : commandLine.getArgs()) { entries.add(load(new File(filename))); } //validate the inputs if (entries.isEmpty()) { throw new IllegalArgumentException("requires at least one file"); } int numberOfRows = -1; int numberOfColumns = -1; for (int i = 0; i < entries.size(); i++) { if (numberOfRows == -1) { numberOfRows = entries.get(i).length; if (numberOfRows == 0) { throw new IllegalArgumentException("empty file: " + commandLine.getArgs()[i]); } } else if (numberOfRows != entries.get(i).length) { throw new IllegalArgumentException("unbalanced rows: " + commandLine.getArgs()[i]); } if (numberOfColumns == -1) { numberOfColumns = entries.get(i)[0].length; } else if (numberOfColumns != entries.get(i)[0].length) { throw new IllegalArgumentException("unbalanced columns: " + commandLine.getArgs()[i]); } } //setup the mode if (commandLine.hasOption("mode")) { mode = completer.lookup(commandLine.getOptionValue("mode")); if (mode == null) { throw new IllegalArgumentException("invalid mode"); } } else { mode = "average"; } try { //instantiate the writer if (commandLine.hasOption("output")) { out = new PrintStream(commandLine.getOptionValue("output")); } else { out = System.out; } //compute the statistics for (int i = 0; i < numberOfRows; i++) { for (int j = 0; j < numberOfColumns; j++) { statistics.clear(); for (int k = 0; k < entries.size(); k++) { double value = entries.get(k)[i][j]; if (Double.isInfinite(value) && commandLine.hasOption("maximum")) { value = Double.parseDouble(commandLine.getOptionValue("maximum")); } if ((Double.isInfinite(value) || Double.isNaN(value)) && commandLine.hasOption("ignore")) { // ignore infinity or NaN values } else { statistics.addValue(value); } } if (j > 0) { out.print(' '); } if (mode.equals("minimum")) { out.print(statistics.getMin()); } else if (mode.equals("maximum")) { out.print(statistics.getMax()); } else if (mode.equals("average")) { out.print(statistics.getMean()); } else if (mode.equals("stdev")) { out.print(statistics.getStandardDeviation()); } else if (mode.equals("count")) { out.print(statistics.getN()); } else { throw new IllegalArgumentException("unknown mode: " + mode); } } out.println(); } } finally { if ((out != null) && (out != System.out)) { out.close(); } } }