Example usage for java.lang Double isNaN

List of usage examples for java.lang Double isNaN

Introduction

In this page you can find the example usage for java.lang Double isNaN.

Prototype

public static boolean isNaN(double v) 

Source Link

Document

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

Usage

From source file:com.rapidminer.operator.preprocessing.filter.TFIDFFilter.java

@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
    if (exampleSet.size() < 1) {
        throw new UserError(this, 110, new Object[] { "1" });
    }/*  w w w.ja va 2s .  com*/
    if (exampleSet.getAttributes().size() == 0) {
        throw new UserError(this, 106, new Object[0]);
    }

    // init
    double[] termFrequencySum = new double[exampleSet.size()];
    List<Attribute> attributes = new LinkedList<Attribute>();
    for (Attribute attribute : exampleSet.getAttributes()) {
        if (attribute.isNumerical()) {
            attributes.add(attribute);
        }
    }
    int[] documentFrequencies = new int[attributes.size()];

    // calculate frequencies
    int index = 0;
    for (Attribute attribute : attributes) {
        int exampleCounter = 0;
        for (Example example : exampleSet) {
            double value = example.getValue(attribute);
            termFrequencySum[exampleCounter] += value;
            if (value > 0) {
                documentFrequencies[index]++;
            }
            exampleCounter++;
        }
        index++;
        checkForStop();
    }

    // calculate IDF values
    double[] inverseDocumentFrequencies = new double[documentFrequencies.length];
    for (int i = 0; i < attributes.size(); i++) {
        inverseDocumentFrequencies[i] = Math.log((double) exampleSet.size() / (double) documentFrequencies[i]);
    }

    // set values
    boolean calculateTermFrequencies = getParameterAsBoolean(PARAMETER_CALCULATE_TERM_FREQUENCIES);
    index = 0;
    for (Attribute attribute : attributes) {
        int exampleCounter = 0;
        for (Example example : exampleSet) {
            double value = example.getValue(attribute);
            if (termFrequencySum[exampleCounter] == 0.0d || Double.isNaN(inverseDocumentFrequencies[index])) {
                example.setValue(attribute, 0.0d);
            } else {
                double tf = value;
                if (calculateTermFrequencies) {
                    tf /= termFrequencySum[exampleCounter];
                }
                double idf = inverseDocumentFrequencies[index];
                example.setValue(attribute, (tf * idf));
            }
            exampleCounter++;
        }
        index++;
        checkForStop();
    }
    return exampleSet;
}

From source file:org.ulyssis.ipp.publisher.Score.java

public Score(Snapshot snapshot, boolean publicScore) {
    Config config = Config.getCurrentConfig();
    Instant now = Instant.now();
    this.time = now.toEpochMilli();
    this.lap = config.getTrackLength();
    this.update = snapshot.getUpdateFrequency();
    this.teams = new TreeSet<>();
    this.status = snapshot.getStatus();
    this.message = snapshot.getStatusMessage();
    TeamStates teamStates = publicScore ? snapshot.getPublicTeamStates() : snapshot.getTeamStates();
    for (org.ulyssis.ipp.config.Team team : config.getTeams()) {
        Optional<TeamState> teamState = teamStates.getStateForTeam(team.getTeamNb());
        if (teamState.isPresent()) {
            TeamState t = teamState.get();
            double speed = t.getPredictedSpeed();
            if (Double.isNaN(speed)) {
                teams.add(new Team(lap, team.getTeamNb(), team.getName(), 0, 0, 0, 0));
            } else {
                TagSeenEvent lastEvent = t.getLastTagSeenEvent().get();
                Instant lastTime = t.getLastTagSeenEvent().get().getTime();
                double elapsedSeconds = Duration.between(lastTime, now).toMillis() / 1000D;
                double previousReaderPosition = config.getReader(lastEvent.getReaderId()).getPosition();
                double nonLimitedPosition = previousReaderPosition + elapsedSeconds * speed;
                double position = nonLimitedPosition;
                if (position > config.getTrackLength())
                    position = config.getTrackLength();
                teams.add(new Team(lap, team.getTeamNb(), team.getName(), t.getNbLaps(),
                        position / config.getTrackLength(), nonLimitedPosition / config.getTrackLength(),
                        speed));//from w  w  w  . j ava 2s. com
            }
        } else {
            teams.add(new Team(lap, team.getTeamNb(), team.getName(), 0, 0, 0, 0));
        }
    }
}

From source file:gdsc.smlm.model.CompoundMoleculeModel.java

/**
 * Check that all the molecules have a valid mass. If any are below zero then set to zero. If all are below zero
 * then set to 1 so that the centre-of-mass is valid.
 *//*w  w  w . j a  v  a  2 s .  c o m*/
public void checkMass() {
    int invalidMass = 0;
    for (MoleculeModel m : molecules) {
        if (m == null)
            throw new IllegalArgumentException("Input list contains null molecules");
        if (m.mass <= 0 || Double.isNaN(m.mass)) {
            invalidMass++;
            //throw new IllegalArgumentException("Input list contains molecules with invalid mass: " + m.mass);
        }
    }

    this.mass = 0;
    if (invalidMass > 0) {
        final double resetMass = (invalidMass == molecules.size()) ? 1 : 0;
        for (MoleculeModel m : molecules) {
            if (m.mass <= 0 || Double.isNaN(m.mass))
                m.mass = resetMass;
            this.mass += m.mass;
        }
    } else {
        for (MoleculeModel m : molecules) {
            this.mass += m.mass;
        }
    }
}

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);//w ww  .  ja  va 2 s  .c  om
    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:com.cloudera.oryx.kmeans.computation.normalize.StandardizeFn.java

@Override
public void process(Record record, Emitter<RealVector> emitter) {
    int len = record.getSpec().size() + expansion;
    RealVector v;//from w  w w. ja  v  a2s.c  om
    if (record instanceof VectorRecord) {
        RealVector innerRecord = ((VectorRecord) record).getVector();
        if (innerRecord instanceof ArrayRealVector) {
            v = Vectors.dense(len);
        } else {
            v = Vectors.sparse(len);
        }
    } else if (sparse) {
        v = Vectors.sparse(len);
    } else {
        v = Vectors.dense(len);
    }
    increment("NORMALIZE", "INPUT_RECORDS");

    int offset = 0;
    for (int i = 0; i < record.getSpec().size(); i++) {
        if (!idColumns.contains(i) && !ignoredColumns.contains(i)) {
            SummaryStats ss = summary.getStats(i);
            if (ss == null || ss.isEmpty()) {
                v.setEntry(offset, record.getAsDouble(i));
                offset++;
            } else if (ss.isNumeric()) {
                Transform t = settings.getTransform(i);
                double raw = record.getAsDouble(i);
                if (Double.isNaN(raw)) {
                    increment("NORMALIZE", "NaN record value");
                    return;
                }
                double n = t.apply(raw, ss) * settings.getScale(i);
                v.setEntry(offset, n);
                offset++;
            } else {
                int index = ss.index(record.getAsString(i));
                if (index < 0) {
                    increment("NORMALIZE", "Negative record index");
                    return;
                }
                v.setEntry(offset + index, settings.getScale(i));
                offset += ss.numLevels();
            }
        }
    }

    increment("NORMALIZE", "PRE_NAMING");
    if (!idColumns.isEmpty()) {
        // TODO: arbitrary properties
        v = new NamedRealVector(v, record.getAsString(idColumns.iterator().next()));
    }
    emitter.emit(v);
    increment("NORMALIZE", "OUTPUT_VECTORS");
}

From source file:com.github.joulupunikki.math.random.BitsStreamGenerator64.java

/**
 * Copied verbatim from super, need to re-implement here since some
 * persistent state used is private in super.
 *
 * @return// w  w w . j a  v  a  2  s .c o  m
 */
@Override
public double nextGaussian() {
    final double random;
    if (Double.isNaN(nextGaussian)) {
        // generate a new pair of gaussian numbers
        final double x = nextDouble();
        final double y = nextDouble();
        final double alpha = 2 * FastMath.PI * x;
        final double r = FastMath.sqrt(-2 * FastMath.log(y));
        random = r * FastMath.cos(alpha);
        nextGaussian = r * FastMath.sin(alpha);
    } else {
        // use the second element of the pair already generated
        random = nextGaussian;
        nextGaussian = Double.NaN;
    }

    return random;
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private void computeDouble() {
    int maxA = getMaximalA();
    aToProb = new double[maxA + 1];

    // 1. compute v(a,b,k,n) i.e. the prob to get b at least a times at fixed positions
    for (int a = 0; a <= maxA; a++) {
        aToProb[a] = exp(logv(a, b, k, n) + binomialCoefficientLog(k, a));
    }//  w ww  .  j av a2  s.  c om

    // 2. compute vd(a,b,k,n) i.e. the prob to get b exactly a times at fixed positions
    // 3. compute vs(a,b,k,n) i.e. the prob to get b exactly a times at any positions
    for (int a = maxA - 1; a >= 0; a--) {
        for (int i = 1; i < k - a + 1 && a + i < aToProb.length; i++) {
            if (aToProb[a + i] > 0) {
                aToProb[a] -= exp(Math.log(aToProb[a + i]) + binomialCoefficientLog(a + i, i));
            }
        }

        if (aToProb[a] < 0 || Double.isNaN(aToProb[a]))
            aToProb[a] = 0;
    }

}

From source file:com.floreantpos.ui.dialog.MiscTicketItemDialog.java

public void doOk() {
    double amount = tfItemPrice.getDouble();
    String itemName = tfItemName.getText();

    if (StringUtils.isEmpty(itemName)) {
        POSMessageDialog.showError(Application.getPosWindow(), Messages.getString("MiscTicketItemDialog.1")); //$NON-NLS-1$
        return;//from  w  ww.j a v a  2s  .  com
    }

    if (Double.isNaN(amount)) {
        amount = 0;
    }

    setCanceled(false);

    ticketItem = new TicketItem();
    ticketItem.setItemCount(1);
    ticketItem.setUnitPrice(amount);
    ticketItem.setName(itemName);
    ticketItem.setCategoryName(com.floreantpos.POSConstants.MISC_BUTTON_TEXT);
    ticketItem.setGroupName(com.floreantpos.POSConstants.MISC_BUTTON_TEXT);
    ticketItem.setShouldPrintToKitchen(true);

    Object selectedObject = cbTax.getSelectedItem();

    if (selectedObject instanceof Tax) {
        Tax tax = (Tax) selectedObject;
        if (tax != null) {
            ticketItem.setTaxRate(tax.getRate());
            TerminalConfig.setMiscItemDefaultTaxId(tax.getId());
        }
    }

    PrinterGroup printerGroup = (PrinterGroup) cbPrinterGroup.getSelectedItem();
    if (printerGroup != null) {
        ticketItem.setPrinterGroup(printerGroup);
    }

    dispose();
}

From source file:com.ning.metrics.collector.util.Stats.java

/**
 * @return min//from  ww  w.j a va 2  s.c  om
 */
@Managed
@SuppressWarnings("unused")
public double getSizeMin() {
    double min = sizeStats.getMin();
    return Double.isNaN(min) ? 0.0 : min;
}

From source file:mase.spec.HybridStat.java

private void printMatrix(double[][] m, EvolutionState state) {
    DecimalFormat df = new DecimalFormat("000.000");
    try {/*ww w.  j a v a2 s. com*/
        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!!");
    }
}