List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:Tsne.java
/** * Convert data to probability//w ww .ja v a 2s .c om * co-occurrences (aka calculating the kernel) * @param d the data to convert * @param u the perplexity of the model * @return the probabilities of co-occurrence */ public INDArray computeGaussianPerplexity(final INDArray d, double u) { int n = d.rows(); final INDArray p = zeros(n, n); final INDArray beta = ones(n, 1); final double logU = Math.log(u); log.info("Calculating probabilities of data similarities.."); for (int i = 0; i < n; i++) { if (i % 500 == 0 && i > 0) log.info("Handled " + i + " records"); double betaMin = Double.NEGATIVE_INFINITY; double betaMax = Double.POSITIVE_INFINITY; NDArrayIndex[] range = new NDArrayIndex[] { NDArrayIndex.concat(NDArrayIndex.interval(0, i), NDArrayIndex.interval(i + 1, d.columns())) }; INDArray row = d.slice(i).get(range); Pair<INDArray, INDArray> pair = hBeta(row, beta.getDouble(i)); INDArray hDiff = pair.getFirst().sub(logU); int tries = 0; //while hdiff > tolerance while (BooleanIndexing.and(abs(hDiff), Conditions.greaterThan(tolerance)) && tries < 50) { //if hdiff > 0 if (BooleanIndexing.and(hDiff, Conditions.greaterThan(0))) { if (Double.isInfinite(betaMax)) beta.putScalar(i, beta.getDouble(i) * 2.0); else beta.putScalar(i, (beta.getDouble(i) + betaMax) / 2.0); betaMin = beta.getDouble(i); } else { if (Double.isInfinite(betaMin)) beta.putScalar(i, beta.getDouble(i) / 2.0); else beta.putScalar(i, (beta.getDouble(i) + betaMin) / 2.0); betaMax = beta.getDouble(i); } pair = hBeta(row, beta.getDouble(i)); hDiff = pair.getFirst().subi(logU); tries++; } p.slice(i).put(range, pair.getSecond()); } //dont need data in memory after log.info("Mean value of sigma " + sqrt(beta.rdiv(1)).mean(Integer.MAX_VALUE)); BooleanIndexing.applyWhere(p, Conditions.isNan(), new Value(realMin)); //set 0 along the diagonal INDArray permute = p.transpose(); INDArray pOut = p.add(permute); pOut.divi(pOut.sum(Integer.MAX_VALUE)); BooleanIndexing.applyWhere(pOut, Conditions.lessThan(Nd4j.EPS_THRESHOLD), new Value(Nd4j.EPS_THRESHOLD)); //ensure no nans return pOut; }
From source file:com.opengamma.analytics.math.minimization.QuasiNewtonVectorMinimizer.java
private boolean getNextPosition(final Function1D<DoubleMatrix1D, Double> function, final Function1D<DoubleMatrix1D, DoubleMatrix1D> grad, final DataBundle data) { final DoubleMatrix1D p = getDirection(data); if (data.getLambda0() < 1.0) { data.setLambda0(1.0);//ww w .j ava 2 s . c om } else { data.setLambda0(data.getLambda0() * BETA); } updatePosition(p, function, data); final double g1 = data.getG1(); // the function is invalid at the new position, try to recover if (Double.isInfinite(g1) || Double.isNaN(g1)) { bisectBacktrack(p, function, data); } if (data.getG1() > data.getG0() / (1 + ALPHA * data.getLambda0())) { quadraticBacktrack(p, function, data); int count = 0; while (data.getG1() > data.getG0() / (1 + ALPHA * data.getLambda0())) { if (count > 5) { return false; } cubicBacktrack(p, function, data); count++; } } final DoubleMatrix1D deltaX = data.getDeltaX(); data.setX((DoubleMatrix1D) MA.add(data.getX(), deltaX)); data.setG0(data.getG1()); final DoubleMatrix1D gradNew = grad.evaluate(data.getX()); data.setDeltaGrad((DoubleMatrix1D) MA.subtract(gradNew, data.getGrad())); data.setGrad(gradNew); return true; }
From source file:hivemall.utils.math.MathUtils.java
/** * Returns the inverse erf. This code is based on erfInv() in * org.apache.commons.math3.special.Erf. * <p>// ww w .j a v a 2 s . co m * This implementation is described in the paper: <a * href="http://people.maths.ox.ac.uk/gilesm/files/gems_erfinv.pdf">Approximating the erfinv * function</a> by Mike Giles, Oxford-Man Institute of Quantitative Finance, which was published * in GPU Computing Gems, volume 2, 2010. The source code is available <a * href="http://gpucomputing.net/?q=node/1828">here</a>. * </p> * * @param x the value * @return t such that x = erf(t) */ public static double inverseErf(final double x) { // beware that the logarithm argument must be // commputed as (1.0 - x) * (1.0 + x), // it must NOT be simplified as 1.0 - x * x as this // would induce rounding errors near the boundaries +/-1 double w = -Math.log((1.0 - x) * (1.0 + x)); double p; if (w < 6.25) { w = w - 3.125; p = -3.6444120640178196996e-21; p = -1.685059138182016589e-19 + p * w; p = 1.2858480715256400167e-18 + p * w; p = 1.115787767802518096e-17 + p * w; p = -1.333171662854620906e-16 + p * w; p = 2.0972767875968561637e-17 + p * w; p = 6.6376381343583238325e-15 + p * w; p = -4.0545662729752068639e-14 + p * w; p = -8.1519341976054721522e-14 + p * w; p = 2.6335093153082322977e-12 + p * w; p = -1.2975133253453532498e-11 + p * w; p = -5.4154120542946279317e-11 + p * w; p = 1.051212273321532285e-09 + p * w; p = -4.1126339803469836976e-09 + p * w; p = -2.9070369957882005086e-08 + p * w; p = 4.2347877827932403518e-07 + p * w; p = -1.3654692000834678645e-06 + p * w; p = -1.3882523362786468719e-05 + p * w; p = 0.0001867342080340571352 + p * w; p = -0.00074070253416626697512 + p * w; p = -0.0060336708714301490533 + p * w; p = 0.24015818242558961693 + p * w; p = 1.6536545626831027356 + p * w; } else if (w < 16.0) { w = Math.sqrt(w) - 3.25; p = 2.2137376921775787049e-09; p = 9.0756561938885390979e-08 + p * w; p = -2.7517406297064545428e-07 + p * w; p = 1.8239629214389227755e-08 + p * w; p = 1.5027403968909827627e-06 + p * w; p = -4.013867526981545969e-06 + p * w; p = 2.9234449089955446044e-06 + p * w; p = 1.2475304481671778723e-05 + p * w; p = -4.7318229009055733981e-05 + p * w; p = 6.8284851459573175448e-05 + p * w; p = 2.4031110387097893999e-05 + p * w; p = -0.0003550375203628474796 + p * w; p = 0.00095328937973738049703 + p * w; p = -0.0016882755560235047313 + p * w; p = 0.0024914420961078508066 + p * w; p = -0.0037512085075692412107 + p * w; p = 0.005370914553590063617 + p * w; p = 1.0052589676941592334 + p * w; p = 3.0838856104922207635 + p * w; } else if (!Double.isInfinite(w)) { w = Math.sqrt(w) - 5.0; p = -2.7109920616438573243e-11; p = -2.5556418169965252055e-10 + p * w; p = 1.5076572693500548083e-09 + p * w; p = -3.7894654401267369937e-09 + p * w; p = 7.6157012080783393804e-09 + p * w; p = -1.4960026627149240478e-08 + p * w; p = 2.9147953450901080826e-08 + p * w; p = -6.7711997758452339498e-08 + p * w; p = 2.2900482228026654717e-07 + p * w; p = -9.9298272942317002539e-07 + p * w; p = 4.5260625972231537039e-06 + p * w; p = -1.9681778105531670567e-05 + p * w; p = 7.5995277030017761139e-05 + p * w; p = -0.00021503011930044477347 + p * w; p = -0.00013871931833623122026 + p * w; p = 1.0103004648645343977 + p * w; p = 4.8499064014085844221 + p * w; } else { // this branch does not appears in the original code, it // was added because the previous branch does not handle // x = +/-1 correctly. In this case, w is positive infinity // and as the first coefficient (-2.71e-11) is negative. // Once the first multiplication is done, p becomes negative // infinity and remains so throughout the polynomial evaluation. // So the branch above incorrectly returns negative infinity // instead of the correct positive infinity. p = Double.POSITIVE_INFINITY; } return p * x; }
From source file:org.jactr.core.model.six.DefaultCycleProcessor6.java
/** * using the current state, guestimate as to the how long this cycle will run * assuming that no production actually fired * //w w w .j a v a2 s.c o m * @return */ protected double calculateNextWaitTime(double now, double productionFiringTime, BasicModel model, boolean eventsHaveFired) { // IProceduralModule procMod = model.getProceduralModule(); // double cycleTime = procMod.getDefaultProductionFiringTime(); TimedEventQueue queue = model.getTimedEventQueue(); /* * if the production queued any events that should fire immediately, we need * to fire them before we guess what the next time should be. */ while (queue.fireExpiredEvents(now)) eventsHaveFired = true; // will already be now+cycleTime if a production fired double nextProductionFiringTime = _nextPossibleProductionFiringTime; double nextEventFiringTime = _nextPossibleProductionFiringTime; double nextWaitTime = nextProductionFiringTime; if (!queue.isEmpty()) nextEventFiringTime = queue.getNextEndTime(); /* * no production fired */ if (Double.isInfinite(productionFiringTime)) if (queue.isEmpty()) { if (!model.isPersistentExecutionEnabled()) { /* * nothing to do, no production fired, and we aren't required to stay * running. lets empty the goal buffer to permit empty productions (w/ * no goal) to fire. if the goal buffer is already empty, signal quit */ IActivationBuffer goalBuffer = model.getActivationBuffer(IActivationBuffer.GOAL); if (goalBuffer.getSourceChunk() != null) goalBuffer.clear(); else return Double.NaN; // signal quit } } else /* * we only skip cycles if no events have fired. If events have fired, * then productions might be able to fire.. */ if (model.isCycleSkippingEnabled() /* && !eventsHaveFired */) { if (eventsHaveFired) nextWaitTime = Math.min(nextEventFiringTime, nextProductionFiringTime); else { nextWaitTime = nextEventFiringTime; nextProductionFiringTime = nextEventFiringTime; } /* * increment the cycles */ long cycleDelta = (long) ((nextWaitTime - now) / model.getProceduralModule().getDefaultProductionFiringTime()); cycleDelta--; model.setCycle(model.getCycle() + cycleDelta); } /* * if the two are absurdly close, just take the larger of the two. this * prevents the occasional situation (w/o cycle skipping) where the * production may fire microseconds before the event is to expire. since no * production fires, the goal is cleared, but then the event fires and there * is no one left to handle it. this prevents the whacky duplicate time * display since the time display is rounded to the millisecond, we're * missing that these are just ever so slightly different */ if (nextEventFiringTime != nextProductionFiringTime && Math.abs(nextProductionFiringTime - nextEventFiringTime) < 0.001) nextWaitTime = Math.max(nextProductionFiringTime, nextEventFiringTime); // // // if (!Double.isInfinite(productionFiringTime)) // nextProductionFiringTime = productionFiringTime + now; // else if (queue.isEmpty()) // { // } // else // { // /* // * no production fired, but we have events to consider. nextWait time is // * minimum of the next event's firing time or the next production firing // * time // */ // nextWaitTime = queue.getNextEndTime(); // // if (!model.isCycleSkippingEnabled()) // { // /* // * if the two are absurdly close, just take the larger of the two. this // * prevents the occasional situation (w/o cycle skipping) where the // * production may fire microseconds before the event is to expire. since // * no production fires, the goal is cleared, but then the event fires // * and there is no one left to handle it. this prevents the whacky // * duplicate time display since the time display is rounded to the // * millisecond, we're missing that these are just ever so slightly // * different // */ // if (Math.abs(_nextPossibleProductionFiringTime - nextWaitTime) < 0.001) // nextWaitTime = Math.max(_nextPossibleProductionFiringTime, // nextWaitTime); // else // nextWaitTime = Math.min(_nextPossibleProductionFiringTime, // nextWaitTime); // } // else // { // // } // // } return nextWaitTime; }
From source file:com.keithcassidy.finishline.LineCrossHandler.java
private void HandleLineCrossing(Location location) { //does this location and bearing intersect with finish line DistanceIntersection diToFinish = LocationUtils.distanceToFinish(location, buoy1, buoy2, finishLineExtension);//from www . j a v a 2 s. c o m sendLocalBroadcast(Constants.FINISHLINE_DISTANCE_MESSAGE, diToFinish.distance); if (isRacing) { //sound appropriate to distance startBeepTimer(PlaySounds.getPeriodFromDistance((int) diToFinish.distance)); //update latest time (used for deciding if service should restart after a crash/reboot PreferencesUtils.setLastRaceStopTime(context, location.getTime()); if (lastLocation != null && lastLocation.distanceTo(location) > LocationUtils.EPSILON) { Log.d(TAG, "last location time " + lastLocation.getTime()); Location locationLookingBack = new Location(location); locationLookingBack.setBearing(locationLookingBack.bearingTo(lastLocation)); DistanceIntersection diBackToFinish = LocationUtils.distanceToFinish(locationLookingBack, buoy1, buoy2, finishLineExtension); if (!Double.isInfinite(diBackToFinish.distance) && diBackToFinish.distance >= 0 && diBackToFinish.intersection != null && (location .distanceTo(diBackToFinish.intersection) <= location.distanceTo(lastLocation))) { long timeOfCrossing = lastLocation.getTime() + (long) ((location.getTime() - lastLocation.getTime()) * (lastLocation.distanceTo(diBackToFinish.intersection) / location.distanceTo(lastLocation))); diBackToFinish.intersection.setTime(timeOfCrossing); diBackToFinish.intersection.setBearing(lastLocation.bearingTo(location)); finishLineDataStorage.addCrossing(diBackToFinish.intersection); sendLocalBroadcast(Constants.FINISHLINE_CROSSED_MESSAGE, true); PlaySounds.playLineCross(context); } } lastLocation = location; } //lastDistanceToFinish = diToFinish.distance; /* if (lastLocation != null && isRacing) { //test to see if we crossed the line if( !Double.isInfinite(lastDistanceToFinish) && lastDistanceToFinish > 0 && diToFinish.distance <= 0 ) { long timeOfCrossing = lastLocation.getTime() + (long)((location.getTime() - lastLocation.getTime()) * (lastDistanceToFinish / (Math.abs(diToFinish.distance) + lastDistanceToFinish)) ) ; Location buoyStart = new Location("na"); buoyStart.setLatitude(buoy1.Position.latitude); buoyStart.setLongitude(buoy1.Position.longitude); Location buoyEnd = new Location("na"); buoyEnd.setLatitude(buoy2.Position.latitude); buoyEnd.setLongitude(buoy2.Position.longitude); buoyEnd.setBearing(buoyEnd.bearingTo(buoyStart)); buoyStart.setBearing(buoyStart.bearingTo(buoyEnd)); //Location locationCrossing = LocationUtils.intersectionOfTwoPaths(lastLocation, buoyStart); if( diToFinish.intersection != null ) { diToFinish.intersection.setTime(timeOfCrossing); diToFinish.intersection.setBearing(lastLocation.getBearing()); finishLineDataStorage.addCrossing(diToFinish.intersection); sendLocalBroadcast(Constants.FINISHLINE_CROSSED_MESSAGE, true); PlaySounds.playLineCross(context); } } } */ }
From source file:FastCache.java
/** * Construct a fast cache of the specified size (measured in * number of hash buckets) and load factor. The size times the * load factor must be greater than or equal to 1. When the * (approximate) number of entries exceeds the load factor times * the size, the cache is pruned./*ww w .jav a 2 s . c o m*/ * * @param size Number of buckets in the cache. * @param loadFactor Load factor of the cache. * @throws IllegalArgumentException If the size is less than one or the load * factor is not a positive finite value. */ public FastCache(int size, double loadFactor) { if (size < 1) { String msg = "Cache size must be at least 1." + " Found cache size=" + size; throw new IllegalArgumentException(msg); } if (loadFactor < 0.0 || Double.isNaN(loadFactor) || Double.isInfinite(loadFactor)) { String msg = "Load factor must be finite and positive." + " found loadFactor=" + loadFactor; throw new IllegalArgumentException(msg); } mMaxEntries = (int) (loadFactor * (double) size); if (mMaxEntries < 1) { String msg = "size * loadFactor must be > 0." + " Found size=" + size + " loadFactor=" + loadFactor; throw new IllegalArgumentException(msg); } // required for array @SuppressWarnings({ "unchecked", "rawtypes" }) SoftReference<Record<K, V>>[] bucketsTemp = (SoftReference<Record<K, V>>[]) new SoftReference[size]; mBuckets = bucketsTemp; }
From source file:org.jactr.core.chunk.four.DefaultSubsymbolicChunk4.java
@Override protected double computeSpreadingActivation() { double spread = 0.0; for (Link jLink : getJAssociations(null)) { ISubsymbolicChunk sc = jLink.getJChunk().getSubsymbolicChunk(); spread += sc.getSourceActivation() * jLink.getStrength(); if (LOGGER.isDebugEnabled()) LOGGER.debug(_parentChunk + " Pulling " + spread + " from " + jLink); }/*from w w w . java 2 s . c o m*/ if (LOGGER.isDebugEnabled()) LOGGER.debug("SpreadingActivation " + spread); if (Double.isNaN(spread) || Double.isInfinite(spread)) spread = 0; return spread; }
From source file:gedi.util.MathUtils.java
public static double saveMax(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.max(a, b); }
From source file:edu.jhuapl.bsp.detector.OpenMath.java
public static double[] mean(double[][] in) { if (in != null) { int M = in.length, N = in[0].length; double sums[] = ones(N, 0); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { sums[i] += in[j][i];// ww w . j a v a2 s. com } sums[i] /= M; if (Double.isNaN(sums[i]) || Double.isInfinite(sums[i])) { sums[i] = 0; } } return sums; } return new double[0]; }
From source file:org.deidentifier.arx.risk.Gamma.java
/** * Approximates the trigamma function. Java port of the * "The Lightspeed Matlab toolbox" version 2.7 by Tom Minka see: * http://research.microsoft.com/en-us/um/people/minka/software/lightspeed/ * //from w w w. j a v a2s . c o m * @param x * input value * @return approximation of trigamma for x */ static double trigamma(double x) { /* Illegal arguments */ if (Double.isInfinite(x) || Double.isNaN(x)) { return Double.NaN; } /* Singularities */ if (x == 0.0d) { return Double.NEGATIVE_INFINITY; } /* Negative values */ /* * Use the derivative of the digamma reflection formula: -trigamma(-x) = * trigamma(x+1) - (pi*csc(pi*x))^2 */ if (x < 0.0d) { double r = StrictMath.PI / StrictMath.sin(-StrictMath.PI * x); return -trigamma(1.0d - x) + (r * r); } /* Use Taylor series if argument <= small */ if (x <= SMALL_TRIGAMMA) { return (1.0d / (x * x)) + TRIGAMMA_1 + (TETRAGAMMA_1 * x); } double result = 0.0d; /* Reduce to trigamma(x+n) where ( X + N ) >= B */ while (x < LARGE_TRIGAMMA) { result += 1.0d / (x * x); x++; } /* Apply asymptotic formula when X >= B */ /* This expansion can be computed in Maple via asympt(Psi(1,x),x) */ if (x >= LARGE_DIGAMMA) { double r = 1.0d / (x * x); result += (0.5d * r) + ((1.0d + (r * (B2 + (r * (B4 + (r * (B6 + (r * (B8 + (r * B10)))))))))) / x); } return result; }