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:Main.java

static double distanceFromPointOnArc(double dA, double dB, double dAB) {
    // In spherical trinagle ABC
    // a is length of arc BC, that is dB
    // b is length of arc AC, that is dA
    // c is length of arc AB, that is dAB
    // We rename parameters so following formulas are more clear:
    double a = dB;
    double b = dA;
    double c = dAB;

    // First, we calculate angles alpha and beta in spherical triangle ABC
    // and based on them we decide how to calculate the distance:
    if (Math.sin(b) * Math.sin(c) == 0.0 || Math.sin(c) * Math.sin(a) == 0.0) {
        // It probably means that one of distance is n*pi, which gives around 20000km for n = 1,
        // unlikely for Denmark, so we should be fine.
        return -1.0;
    }/* w  w  w  .j a va 2 s.co m*/

    double alpha = Math.acos((Math.cos(a) - Math.cos(b) * Math.cos(c)) / (Math.sin(b) * Math.sin(c)));
    double beta = Math.acos((Math.cos(b) - Math.cos(c) * Math.cos(a)) / (Math.sin(c) * Math.sin(a)));

    // It is possible that both sinuses are too small so we can get nan when dividing with them
    if (Double.isNaN(alpha) || Double.isNaN(beta)) {
        return -1.0;
    }

    // If alpha or beta are zero or pi, it means that C is on the same circle as arc AB,
    // we just need to figure out if it is between AB:
    if (alpha == 0.0 || beta == 0.0) {
        return (dA + dB > dAB) ? Math.min(dA, dB) : 0.0;
    }

    // If alpha is obtuse and beta is acute angle, then
    // distance is equal to dA:
    if (alpha > Math.PI / 2 && beta < Math.PI / 2)
        return -1;

    // Analogously, if beta is obtuse and alpha is acute angle, then
    // distance is equal to dB:
    if (beta > Math.PI / 2 && alpha < Math.PI / 2)
        return -1;

    // Again, unlikely, since it would render at least pi/2*EARTH_RADIUS_IN_METERS, which is too much.
    if (Math.cos(a) == 0.0)
        return -1;

    double x = Math.atan(-1.0 / Math.tan(c) + (Math.cos(b) / (Math.cos(a) * Math.sin(c))));

    return x;
}

From source file:Main.java

/**
 * applies a 6th-order butterworth highpass filter with cutoff at 0.6
 * @param data/* w ww . j av a2  s  .co m*/
 * @return highpass filtered data
 */
public static double[] applyHighPassFilter(double[] data) {

    //http://dsp.stackexchange.com/questions/592/how-does-matlab-handle-iir-filters

    double xmem1, xmem2, ymem1, ymem2, xmem3, xmem4, ymem3, ymem4, xmem5, xmem6, ymem5, ymem6;
    xmem1 = xmem2 = ymem1 = ymem2 = xmem3 = xmem4 = ymem3 = ymem4 = xmem5 = xmem6 = ymem5 = ymem6 = 0.0;

    int p = 0;

    while (p < data.length) {

        double y = b[0] * data[p] + b[1] * xmem1 + b[2] * xmem2 + b[3] * xmem3 + b[4] * xmem4 + b[5] * xmem5
                + b[6] * xmem6 - a[1] * ymem1 - a[2] * ymem2 - a[3] * ymem3 - a[4] * ymem4 - a[5] * ymem5
                - a[6] * ymem6;

        if (Double.isNaN(y))
            y = 0.0;

        xmem6 = xmem5;
        xmem5 = xmem4;
        xmem4 = xmem3;
        xmem3 = xmem2;
        xmem2 = xmem1;
        xmem1 = data[p];
        ymem6 = ymem5;
        ymem5 = ymem4;
        ymem4 = ymem3;
        ymem3 = ymem2;
        ymem2 = ymem1;
        ymem1 = y;

        data[p] = y;

        p++;
    }
    return data;

}

From source file:com.analog.lyric.math.LyricSingularValueDecomposition.java

private static RealMatrix checkMatrix(RealMatrix m) {
    for (int i = 0; i < m.getRowDimension(); i++) {
        for (int j = 0; j < m.getColumnDimension(); j++) {
            if (Double.isNaN(m.getEntry(i, j)) || Double.isInfinite(m.getEntry(i, j))) {
                throw new DimpleException("cannot do SVD on matrix that contains NaN or infinite");
            }//from  w  w w. j  a  v a 2 s . c  o m
        }
    }
    return m;
}

From source file:geogebra.util.MyMath.java

final public static double sgn(Kernel kernel, double a) {

    // bugfix for graph f(x) = sgn(sqrt(1 - x))
    if (Double.isNaN(a))
        return Double.NaN;

    if (Kernel.isZero(a))
        return 0.0;
    else if (a > 0.0)
        return 1.0;
    else// www  . j  av a  2 s  .  c om
        return -1.0;
}

From source file:Main.java

/**
 * Returns the <a href="http://mathworld.wolfram.com/Sign.html"> sign</a>
 * for double precision <code>x</code>.
 * <p>/*ww w  .j  a  va 2s. c o  m*/
 * For a double value <code>x</code>, this method returns
 * <code>+1.0</code> if <code>x > 0</code>, <code>0.0</code> if
 * <code>x = 0.0</code>, and <code>-1.0</code> if <code>x < 0</code>.
 * Returns <code>NaN</code> if <code>x</code> is <code>NaN</code>.</p>
 * 
 * @param x the value, a double
 * @return +1.0, 0.0, or -1.0, depending on the sign of x
 */
public static double sign(final double x) {
    if (Double.isNaN(x)) {
        return Double.NaN;
    }
    return (x == 0.0) ? 0.0 : (x > 0.0) ? 1.0 : -1.0;
}

From source file:com.algoTrader.util.RoundUtil.java

public static BigDecimal getBigDecimal(double value) {

    if (!Double.isNaN(value)) {
        BigDecimal decimal = new BigDecimal(value);
        return decimal.setScale(PORTFOLIO_DIGITS, BigDecimal.ROUND_HALF_UP);
    } else {/*from   w  w  w .  j a v  a  2s  .  c  o  m*/
        return null;
    }
}

From source file:de.mpicbg.knime.hcs.base.utils.Table2Matrix.java

public static RealMatrix extractMatrix(List<DataRow> rows, List<Attribute> params) {
    double[][] matrix = new double[rows.size()][params.size()];
    int nbparams = params.size();
    int m = 0;//  w w  w  .  j  a  v a  2  s .  c  om
    for (DataRow row : rows) {
        int n = 0;
        for (Attribute readout : params) {
            Double val = readout.getDoubleAttribute(row);
            if ((val == null) || Double.isInfinite(val) || Double.isNaN(val)) {
                break;
            }
            matrix[m][n] = val;
            n += 1;
        }
        if (n == nbparams) {
            m += 1;
        }
    }
    // remove the unused rows.
    RealMatrix rmatrix = new Array2DRowRealMatrix(matrix);
    if (m > 0) {
        rmatrix = rmatrix.getSubMatrix(0, m - 1, 0, nbparams - 1);
    }
    return rmatrix;
}

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args/* www .  jav a 2s  .c  om*/
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:Main.java

/**
 * Sorts a given array of doubles in ascending order and returns an array of
 * integers with the positions of the elements of the original array in the
 * sorted array.//from www  .  j  av a 2 s . c  o m
 *
 * NOTE: this array is not changed by the method!
 *
 * @param array
 *            this array is not changed by the method!
 * @return an array of integers with the positions in the sorted array.
 */
public static int[] sort(double[] array) {

    int[] index = new int[array.length];
    array = (double[]) array.clone();
    for (int i = 0; i < index.length; i++) {
        index[i] = i;
        if (Double.isNaN(array[i])) {
            array[i] = Double.MAX_VALUE;
        }
    }
    quickSort(array, index, 0, array.length - 1);
    return index;
}

From source file:Main.java

/**
 * Normalizes the doubles in the array using the given value.
 *
 * @param doubles/*  w  w w. j  a va  2s .c  o m*/
 *            the array of double
 * @param sum
 *            the value by which the doubles are to be normalized
 * @exception IllegalArgumentException
 *                if sum is zero or NaN
 */
public static void normalize(double[] doubles, double sum) {
    if (Double.isNaN(sum)) {
        throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
    }
    if (sum == 0) {
        return;
    }
    for (int i = 0; i < doubles.length; i++) {
        doubles[i] /= sum;
    }
}