Example usage for java.lang Double NEGATIVE_INFINITY

List of usage examples for java.lang Double NEGATIVE_INFINITY

Introduction

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

Prototype

double NEGATIVE_INFINITY

To view the source code for java.lang Double NEGATIVE_INFINITY.

Click Source Link

Document

A constant holding the negative infinity of type double .

Usage

From source file:com.clust4j.algo.AffinityPropagation.java

/**
 * Computes the first portion of the AffinityPropagation iteration
 * sequence in place. Separating this piece from the {@link #fit()} method
 * itself allows for easier testing.//www  .  j av  a  2s .c om
 * @param A
 * @param S
 * @param tmp
 * @param I
 * @param Y
 * @param Y2
 */
protected static void affinityPiece1(double[][] A, double[][] S, double[][] tmp, int[] I, double[] Y,
        double[] Y2) {
    final int m = S.length;

    // Reassign tmp, create vector of arg maxes. Can
    // assign tmp like this:
    //
    //      tmp = MatUtils.add(A, sim_mat);
    //
    //
    // But requires extra M x M pass. Also get indices of ROW max. 
    // Can do like this:
    //
    //      I = MatUtils.argMax(tmp, Axis.ROW);
    //
    // But requires extra pass on order of M. Finally, capture the second
    // highest record in each row, and store in a vector. Then row-wise
    // scalar subtract Y from the sim_mat
    for (int i = 0; i < m; i++) {

        // Compute row maxes
        double runningMax = Double.NEGATIVE_INFINITY;
        double secondMax = Double.NEGATIVE_INFINITY;
        int runningMaxIdx = 0; //-1; // Idx of max row element -- start at 0 in case metric produces -Infs

        for (int j = 0; j < m; j++) { // Create tmp as A + sim_mat
            tmp[i][j] = A[i][j] + S[i][j];

            if (tmp[i][j] > runningMax) {
                secondMax = runningMax;
                runningMax = tmp[i][j];
                runningMaxIdx = j;
            } else if (tmp[i][j] > secondMax) {
                secondMax = tmp[i][j];
            }
        }

        I[i] = runningMaxIdx; // Idx of max element for row
        Y[i] = tmp[i][I[i]]; // Grab the current val
        Y2[i] = secondMax;
        tmp[i][I[i]] = Double.NEGATIVE_INFINITY; // Set that idx to neg inf now
    }
}

From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java

/**
* The dual delta (first derivative of option price with respect to strike)
* @param spot The spot value of the underlying
* @param strike The Strike//www.  java2  s.  c  o  m
* @param timeToExpiry The time-to-expiry
* @param lognormalVol The log-normal volatility
* @param interestRate The interest rate 
* @param costOfCarry The cost-of-carry  rate
* @param isCall true for call
* @return The dual delta
*/
@ExternalFunction
public static double dualDelta(final double spot, final double strike, final double timeToExpiry,
        final double lognormalVol, final double interestRate, final double costOfCarry, final boolean isCall) {
    ArgumentChecker.isTrue(spot >= 0.0, "negative/NaN spot; have {}", spot);
    ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);
    ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN");
    ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN");

    double discount = 0.;
    if (-interestRate > LARGE) {
        return isCall ? Double.NEGATIVE_INFINITY : (costOfCarry > LARGE ? 0. : Double.POSITIVE_INFINITY);
    }
    if (interestRate > LARGE) {
        return 0.;
    }
    discount = (Math.abs(interestRate) < SMALL && timeToExpiry > LARGE) ? 1.
            : Math.exp(-interestRate * timeToExpiry);

    if (spot > LARGE * strike) {
        return isCall ? -discount : 0.;
    }
    if (spot < SMALL * strike) {
        return isCall ? 0. : discount;
    }

    final int sign = isCall ? 1 : -1;
    final double rootT = Math.sqrt(timeToExpiry);
    double sigmaRootT = lognormalVol * rootT;
    if (Double.isNaN(sigmaRootT)) {
        sigmaRootT = 1.; //ref value is returned
    }

    double factor = Math.exp(costOfCarry * timeToExpiry);
    if (Double.isNaN(factor)) {
        factor = 1.; //ref value is returned
    }
    double rescaledSpot = spot * factor;

    double d2 = 0.;
    if (Math.abs(spot - strike) < SMALL || sigmaRootT > LARGE || (spot > LARGE && strike > LARGE)) {
        final double coefD2 = (costOfCarry / lognormalVol - 0.5 * lognormalVol);
        final double tmp = coefD2 * rootT;
        d2 = Double.isNaN(tmp) ? 0. : tmp;
    } else {
        if (sigmaRootT < SMALL) {
            return isCall ? (rescaledSpot > strike ? -discount : 0.) : (rescaledSpot < strike ? discount : 0.);
        }
        final double tmp = costOfCarry * rootT / lognormalVol;
        final double sig = (costOfCarry >= 0.) ? 1. : -1.;
        final double scnd = Double.isNaN(tmp)
                ? ((lognormalVol < LARGE && lognormalVol > SMALL) ? sig / lognormalVol : sig * rootT)
                : tmp;
        d2 = Math.log(spot / strike) / sigmaRootT + scnd - 0.5 * sigmaRootT;
    }
    //    if (Double.isNaN(d2)) {
    //      throw new IllegalArgumentException("NaN found");
    //    }
    final double norm = NORMAL.getCDF(sign * d2);

    return norm < SMALL ? 0. : -sign * discount * norm;
}

From source file:org.apache.drill.exec.fn.impl.TestNewMathFunctions.java

@Test
public void testLog10WithUint4() throws Exception {
    org.apache.hadoop.fs.Path file = new org.apache.hadoop.fs.Path(dirTestWatcher.getRootDir().toString(),
            "uint8.parquet");
    String schemaText = "message test { required int32 val(UINT_8); }";

    Configuration conf = new Configuration();
    MessageType schema = MessageTypeParser.parseMessageType(schemaText);
    GroupWriteSupport.setSchema(schema, conf);
    SimpleGroupFactory groupFactory = new SimpleGroupFactory(schema);

    try {// w w w .  j a v a 2s.c  o m
        try (ParquetWriter<Group> writer = new ParquetWriter<>(file, new GroupWriteSupport(),
                CompressionCodecName.UNCOMPRESSED, 1024, 1024, 512, true, false,
                ParquetProperties.WriterVersion.PARQUET_1_0, conf)) {

            writer.write(groupFactory.newGroup().append("val", 0));
            writer.write(groupFactory.newGroup().append("val", 1));
            writer.write(groupFactory.newGroup().append("val", -1));
            writer.write(groupFactory.newGroup().append("val", 10));
        }
        String query = "select log10(val) as col from dfs.`uint8.parquet`";
        testBuilder().sqlQuery(query).unOrdered().baselineColumns("col")
                .baselineValues(Double.NEGATIVE_INFINITY).baselineValues(0d).baselineValues(Double.NaN)
                .baselineValues(1.0d).build().run();
    } finally {
        FileUtils.deleteQuietly(new File(file.toString()));
    }
}

From source file:org.jfree.data.time.TimeSeriesCollectionTest.java

/**
 * A test to cover bug 3445507.//from   ww w .  j a  v a2  s.  com
 */
@Test
public void testBug3445507() {
    TimeSeries s1 = new TimeSeries("S1");
    s1.add(new Year(2011), null);
    s1.add(new Year(2012), null);

    TimeSeries s2 = new TimeSeries("S2");
    s2.add(new Year(2011), 5.0);
    s2.add(new Year(2012), 6.0);

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    dataset.addSeries(s2);

    List keys = new ArrayList();
    keys.add("S1");
    keys.add("S2");
    Range r = dataset.getRangeBounds(keys, new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY),
            false);
    assertEquals(5.0, r.getLowerBound(), EPSILON);
    assertEquals(6.0, r.getUpperBound(), EPSILON);
}

From source file:edu.byu.nlp.util.Matrices.java

public static int[] getGreedyRowReorderingForStrongDiagonal(double[][] mat) {
    Preconditions.checkNotNull(mat);// www.  ja  va 2 s  .c  o  m
    int numRows = mat.length;
    int numCols = (mat.length == 0) ? 0 : mat[0].length;

    // order rows in descending order by entry value
    // so that more confident rows get first choice
    int[] rowOrder = getRowReorderingByMaxEntryDesc(mat);

    int[] map = new int[numRows];
    Arrays.fill(map, -1);
    for (int i = 0; i < numRows; i++) {
        int row = IntArrays.indexOf(i, rowOrder, 0, rowOrder.length);

        int maxcol = -1;
        double max = Double.NEGATIVE_INFINITY;
        for (int col = 0; col < numCols; col++) {
            if (mat[row][col] > max) {
                // Only choose this index if we haven't already used it (greedy)
                if (IntArrays.indexOf(col, map, 0, map.length) == -1) {
                    max = mat[row][col];
                    maxcol = col;
                }
            }
        }
        // assign the original row index a new destination (to put it on the diag) 
        map[row] = maxcol;
    }
    assert isValidMap(map);
    return map;
}

From source file:com.joptimizer.optimizers.LPStandardConverterTest.java

/**
 * Standardization of a problem on the form:
 * min(c) s.t.//from  w w w.  j  ava  2  s.  co  m
 * G.x < h
 * A.x = b
 */
public void testCGhAb2() throws Exception {
    log.debug("testCGhAb2");

    String problemId = "2";

    double[] c = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "c" + problemId + ".txt");
    double[][] G = Utils.loadDoubleMatrixFromFile(
            "lp" + File.separator + "standardization" + File.separator + "G" + problemId + ".csv",
            ",".charAt(0));
    double[] h = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "h" + problemId + ".txt");
    ;
    double[][] A = Utils.loadDoubleMatrixFromFile(
            "lp" + File.separator + "standardization" + File.separator + "A" + problemId + ".csv",
            ",".charAt(0));
    double[] b = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "b" + problemId + ".txt");
    double[] expectedSol = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "sol" + problemId + ".txt");
    double expectedValue = Utils.loadDoubleArrayFromFile(
            "lp" + File.separator + "standardization" + File.separator + "value" + problemId + ".txt")[0];
    double expectedTolerance = MatrixUtils.createRealMatrix(A)
            .operate(MatrixUtils.createRealVector(expectedSol)).subtract(MatrixUtils.createRealVector(b))
            .getNorm();

    //standard form conversion
    double unboundedLBValue = Double.NEGATIVE_INFINITY;
    double unboundedUBValue = Double.POSITIVE_INFINITY;
    LPStandardConverter lpConverter = new LPStandardConverter(unboundedLBValue, unboundedUBValue);
    lpConverter.toStandardForm(c, G, h, A, b, null, null);

    int n = lpConverter.getStandardN();
    int s = lpConverter.getStandardS();
    c = lpConverter.getStandardC().toArray();
    A = lpConverter.getStandardA().toArray();
    b = lpConverter.getStandardB().toArray();
    double[] lb = lpConverter.getStandardLB().toArray();
    double[] ub = lpConverter.getStandardUB().toArray();
    log.debug("n : " + n);
    log.debug("s : " + s);
    log.debug("c : " + ArrayUtils.toString(c));
    log.debug("A : " + ArrayUtils.toString(A));
    log.debug("b : " + ArrayUtils.toString(b));
    log.debug("lb : " + ArrayUtils.toString(lb));
    log.debug("ub : " + ArrayUtils.toString(ub));

    //check consistency
    assertEquals(G.length, s);
    assertEquals(A[0].length, n);
    assertEquals(s + lpConverter.getOriginalN(), n);
    assertEquals(lb.length, n);
    assertEquals(ub.length, n);

    //check constraints
    RealMatrix GOrig = new Array2DRowRealMatrix(G);
    RealVector hOrig = new ArrayRealVector(h);
    RealMatrix AStandard = new Array2DRowRealMatrix(A);
    RealVector bStandard = new ArrayRealVector(b);
    RealVector expectedSolVector = new ArrayRealVector(expectedSol);
    RealVector Gxh = GOrig.operate(expectedSolVector).subtract(hOrig);//G.x - h
    RealVector slackVariables = new ArrayRealVector(s);
    for (int i = 0; i < s; i++) {
        slackVariables.setEntry(i, 0. - Gxh.getEntry(i));//the difference from 0
        assertTrue(slackVariables.getEntry(i) >= 0.);
    }
    RealVector sol = slackVariables.append(expectedSolVector);
    RealVector Axmb = AStandard.operate(sol).subtract(bStandard);
    assertEquals(0., Axmb.getNorm(), expectedTolerance);

    //      Utils.writeDoubleArrayToFile(new double[]{s}, "target" + File.separator   + "standardS"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(c, "target" + File.separator   + "standardC"+problemId+".txt");
    //      Utils.writeDoubleMatrixToFile(A, "target" + File.separator   + "standardA"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(b, "target" + File.separator   + "standardB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(lb, "target" + File.separator   + "standardLB"+problemId+".txt");
    //      Utils.writeDoubleArrayToFile(ub, "target" + File.separator   + "standardUB"+problemId+".txt");
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java

private void addAvaregeSeries(TimeSeries series, XYPlot plot) {
    logger.debug("IN");
    boolean isFirst = true;
    double avg = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
    int count = 0;
    for (int i = 0; i < series.getItemCount(); i++) {
        if (series.getValue(i) != null) {
            count++;//from  w ww. j a  v a 2  s . co m
            if (isFirst) {
                min = series.getValue(i).doubleValue();
                max = series.getValue(i).doubleValue();
                isFirst = false;
            }
            double n = series.getValue(i).doubleValue();
            avg += n;
            if (n < min)
                min = n;
            if (n > max)
                max = n;
            logger.debug(n);
        }

    }
    avg = avg / (double) count;

    //plot.getRangeAxis().setRange(new Range(min-2, max+2));

    addMarker(1, avg, colorAverage, 0.8f, plot);
    logger.debug("OUT");

}

From source file:de.thkwalter.et.ortskurve.Startpunktbestimmung.java

/**
 * Diese Methode bestimmt den Messpunkt mit dem grten Wert der x- bzw. y-Komponente.
 * /*w w  w . j  ava2s .  c om*/
 * @param liste Eine Liste der x- bzw. y-Komponenten der Messpunkte
 * 
 * @return Der Messpunkt mit dem grten Wert der x- bzw. y-Komponente
 */
private static Vector2D maxMesspunktBestimmen(ArrayList<? extends KomponenteMesspunkt> liste) {
    // Die Messpunkte mit der grten x- bzw. y-Komponente.
    KomponenteMesspunkt maxKomponenteMesspunkt = null;

    // Die x- bzw. y-Komponente eines Messwertes.
    double wert = Double.NaN;

    // Die grte bisher gefundene x- bzw. y-Komponente.
    double maxWert = Double.NEGATIVE_INFINITY;

    // Eine Schleife ber alle Messpunkte in der Liste
    for (KomponenteMesspunkt komponenteMesspunkt : liste) {
        // Die x- bzw. y-Komponente des Messpunktes wird gelesen.
        wert = komponenteMesspunkt.getWert();

        // Falls die x- bzw. y-Komponente des Messpunkts grer als die grte bisher gefundene x- bzw. y-Komponente, ...
        if (wert > maxWert) {
            // Die grte bisher gefundene x- bzw. y-Komponente wird aktualisiert.  
            maxWert = wert;

            // Der Messpunkt mit der grten x- bzw. y-Komponente wird aktualisiert.
            maxKomponenteMesspunkt = komponenteMesspunkt;
        }
    }

    // Der Messpunkt mit der grten x- bzw. y-Komponente wird aus der Liste entfernt.
    liste.remove(maxKomponenteMesspunkt);

    // Der Messpunkt mit der grten x- bzw. y-Komponente wird zurckgegeben.
    return maxKomponenteMesspunkt.getMesspunkt();
}

From source file:org.jfree.data.jdbc.JDBCXYDataset.java

/**
 * ExecuteQuery will attempt execute the query passed to it against the
 * provided database connection.  If connection is null then no action is
 * taken./*from  w  w  w . j a v  a2 s  .c  om*/
 *
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed.
 * @param  con  the connection the query is to be executed against.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    if (con == null) {
        throw new SQLException("There is no database to execute the query.");
    }

    ResultSet resultSet = null;
    Statement statement = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int numberOfColumns = metaData.getColumnCount();
        int numberOfValidColumns = 0;
        int[] columnTypes = new int[numberOfColumns];
        for (int column = 0; column < numberOfColumns; column++) {
            try {
                int type = metaData.getColumnType(column + 1);
                switch (type) {

                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIT:
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                case Types.BIGINT:
                case Types.SMALLINT:
                    ++numberOfValidColumns;
                    columnTypes[column] = type;
                    break;
                default:
                    columnTypes[column] = Types.NULL;
                    break;
                }
            } catch (SQLException e) {
                columnTypes[column] = Types.NULL;
                throw e;
            }
        }

        if (numberOfValidColumns <= 1) {
            throw new SQLException("Not enough valid columns where generated by query.");
        }

        /// First column is X data
        this.columnNames = new String[numberOfValidColumns - 1];
        /// Get the column names and cache them.
        int currentColumn = 0;
        for (int column = 1; column < numberOfColumns; column++) {
            if (columnTypes[column] != Types.NULL) {
                this.columnNames[currentColumn] = metaData.getColumnLabel(column + 1);
                ++currentColumn;
            }
        }

        // Might need to add, to free memory from any previous result sets
        if (this.rows != null) {
            for (int column = 0; column < this.rows.size(); column++) {
                ArrayList row = (ArrayList) this.rows.get(column);
                row.clear();
            }
            this.rows.clear();
        }

        // Are we working with a time series.
        switch (columnTypes[0]) {
        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            this.isTimeSeries = true;
            break;
        default:
            this.isTimeSeries = false;
            break;
        }

        // Get all rows.
        // rows = new ArrayList();
        while (resultSet.next()) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                Object xObject = resultSet.getObject(column + 1);
                switch (columnTypes[column]) {
                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIGINT:
                case Types.SMALLINT:
                    newRow.add(xObject);
                    break;

                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                    newRow.add(new Long(((Date) xObject).getTime()));
                    break;
                case Types.NULL:
                    break;
                default:
                    System.err.println("Unknown data");
                    columnTypes[column] = Types.NULL;
                    break;
                }
            }
            this.rows.add(newRow);
        }

        /// a kludge to make everything work when no rows returned
        if (this.rows.size() == 0) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                if (columnTypes[column] != Types.NULL) {
                    newRow.add(new Integer(0));
                }
            }
            this.rows.add(newRow);
        }

        /// Determine max and min values.
        if (this.rows.size() < 1) {
            this.maxValue = 0.0;
            this.minValue = 0.0;
        } else {
            ArrayList row = (ArrayList) this.rows.get(0);
            this.maxValue = Double.NEGATIVE_INFINITY;
            this.minValue = Double.POSITIVE_INFINITY;
            for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) {
                row = (ArrayList) this.rows.get(rowNum);
                for (int column = 1; column < numberOfColumns; column++) {
                    Object testValue = row.get(column);
                    if (testValue != null) {
                        double test = ((Number) testValue).doubleValue();

                        if (test < this.minValue) {
                            this.minValue = test;
                        }
                        if (test > this.maxValue) {
                            this.maxValue = test;
                        }
                    }
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
    }

}

From source file:com.duy.pascal.interperter.libraries.math.MathLib.java

@PascalMethod(description = "")
public boolean IsInfinite(double x) {
    return Double.POSITIVE_INFINITY == x || Double.NEGATIVE_INFINITY == x;
}