Example usage for java.lang Math ulp

List of usage examples for java.lang Math ulp

Introduction

In this page you can find the example usage for java.lang Math ulp.

Prototype

public static float ulp(float f) 

Source Link

Document

Returns the size of an ulp of the argument.

Usage

From source file:Main.java

public static void main(String[] args) {

    double x = 123.456;
    double y = 123.1;

    // print the ulp of these doubles
    System.out.println("Math.ulp(" + x + ")=" + Math.ulp(x));
    System.out.println("Math.ulp(" + y + ")=" + Math.ulp(y));

}

From source file:Main.java

public static void main(String[] args) {

    // get two double float numbers
    float x = 123.456f;
    float y = 123.1f;

    // print the ulp of these floats
    System.out.println("Math.ulp(" + x + ")=" + Math.ulp(x));
    System.out.println("Math.ulp(" + y + ")=" + Math.ulp(y));

}

From source file:com.mgmtp.jfunk.common.random.MathRandom.java

/**
 * Returns a random decimal number in the range of [0, max].
 * //from www.j a v a 2 s. c o m
 * @param max
 *            maximum value for generated number
 */
public double getDouble(final double max) {
    return (max + Math.ulp(max)) * random.nextDouble();
}

From source file:eu.crisis_economics.utilities.EnumDistribution.java

public static <T extends Enum<T>> EnumDistribution<T> // Immutable
        create(Class<T> token, String sourceFile) throws IOException {
    if (token == null)
        throw new NullArgumentException();
    if (!token.isEnum())
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is not an enum.");
    if (token.getEnumConstants().length == 0)
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is an empty enum.");
    EnumDistribution<T> result = new EnumDistribution<T>();
    result.values = token.getEnumConstants();
    result.probabilities = new EnumMap<T, Double>(token);
    Map<String, T> converter = new HashMap<String, T>();
    final int numberOfValues = result.values.length;
    int[] valueIndices = new int[numberOfValues];
    double[] valueProbabilities = new double[numberOfValues];
    BitSet valueIsComitted = new BitSet(numberOfValues);
    {//from   w ww  .  j a  va 2  s  .c o  m
        int counter = 0;
        for (T value : result.values) {
            valueIndices[counter] = counter++;
            result.probabilities.put(value, 0.);
            converter.put(value.name(), value);
        }
    }
    BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
    try {
        String newLine;
        while ((newLine = reader.readLine()) != null) {
            if (newLine.isEmpty())
                continue;
            StringTokenizer tokenizer = new StringTokenizer(newLine);
            final String name = tokenizer.nextToken(" ,:\t"), pStr = tokenizer.nextToken(" ,:\t");
            if (tokenizer.hasMoreTokens())
                throw new ParseException(
                        "EnumDistribution: " + newLine + " is not a valid entry in " + sourceFile + ".", 0);
            final double p = Double.parseDouble(pStr);
            if (p < 0. || p > 1.)
                throw new IOException(pStr + " is not a valid probability for the value " + name);
            result.probabilities.put(converter.get(name), p);
            final int ordinal = converter.get(name).ordinal();
            if (valueIsComitted.get(ordinal))
                throw new ParseException("The value " + name + " appears twice in " + sourceFile, 0);
            valueProbabilities[converter.get(name).ordinal()] = p;
            valueIsComitted.set(ordinal, true);
        }
        { // Check sum of probabilities
            double sum = 0.;
            for (double p : valueProbabilities)
                sum += p;
            if (Math.abs(sum - 1.) > 1e2 * Math.ulp(1.))
                throw new IllegalStateException("EnumDistribution: parser has succeeded, but the resulting "
                        + "probaility sum (value " + sum + ") is not equal to 1.");
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        reader.close();
    }
    result.dice = new EnumeratedIntegerDistribution(valueIndices, valueProbabilities);
    return result;
}

From source file:edu.umn.cs.spatialHadoop.core.OGCJTSShape.java

@Override
public Rectangle getMBR() {
    if (geom == null)
        return null;
    Coordinate[] coords = geom.getEnvelope().getCoordinates();
    if (coords.length == 0)
        return null;
    double xmin, ymin, xmax, ymax;
    if (coords.length == 1) {
        // A point
        xmin = coords[0].x;// w ww . j ava2  s. co m
        ymin = coords[0].y;
        xmax = xmin + Math.ulp(xmin);
        ymax = ymin + Math.ulp(ymin);
    } else if (coords.length == 2) {
        // An orthogonal line
        if (coords[0].x == coords[1].x) {
            // A vertical line
            xmin = coords[0].x;
            xmax = xmin + Math.ulp(xmin);
            ymin = Math.min(coords[0].y, coords[1].y);
            ymax = Math.max(coords[0].y, coords[1].y);
        } else {
            // A horizontal line
            xmin = Math.min(coords[0].x, coords[1].x);
            xmax = Math.max(coords[0].x, coords[1].x);
            ymin = coords[0].y;
            ymax = ymin + Math.ulp(ymin);
        }
    } else if (coords.length == 4 || coords.length == 5) {
        // A rectangle
        xmin = Math.min(coords[0].x, coords[2].x);
        ymin = Math.min(coords[0].y, coords[2].y);
        xmax = Math.max(coords[0].x, coords[2].x);
        ymax = Math.max(coords[0].y, coords[2].y);
    } else {
        throw new RuntimeException("Cannot get MBR of " + geom);
    }

    return new Rectangle(xmin, ymin, xmax, ymax);
}

From source file:com.analog.lyric.dimple.test.solvers.sumproduct.TestSampledFactors.java

/**
 * Generates a random covariance matrix with given dimension.
 *///from  ww w.java  2 s . co  m
RealMatrix randCovariance(int n) {
    RealMatrix A = MatrixUtils.createRealMatrix(n, n);

    // Randomize
    A.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return testRand.nextDouble();
        }
    });

    RealMatrix B = A.add(A.transpose()); // B is symmetric
    double minEig = Doubles.min(new EigenDecomposition(B).getRealEigenvalues());
    double r = testRand.nextGaussian();
    r *= r;
    r += Math.ulp(1.0);
    RealMatrix I = MatrixUtils.createRealIdentityMatrix(n);
    RealMatrix C = B.add(I.scalarMultiply(r - minEig));

    return C;
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@link POSITIVE_INFINITY} in BigDecimal.
 *
 * @param type Float or Double.//  www  . ja  v a 2s .  c  o  m
 * @return POSITIVE_INFINITY in BigDecimal.
 */
private static final BigDecimal toInfinityAndBeyond(Class<? extends Number> type) {
    if (Double.class.equals(type))
        return new BigDecimal(Double.MAX_VALUE).add(new BigDecimal(Math.ulp(Double.MAX_VALUE) / 2));
    if (Float.class.equals(type))
        return new BigDecimal(Float.MAX_VALUE).add(new BigDecimal(Math.ulp(Float.MAX_VALUE) / 2));

    throw new IllegalArgumentException("the type \"" + type + "\" are not implements Infinities.");
}

From source file:org.orekit.propagation.AbstractPropagator.java

/** Add an event handler for end date checking.
 * <p>This method can be used to simplify handling of integration end date.
 * It leverages the nominal stop condition with the exceptional stop
 * conditions.</p>// ww  w  .j ava  2 s .  co m
 * @param startDate propagation start date
 * @param endDate desired end date
 * @param manager manager containing the user-defined handlers
 * @return a new manager containing all the user-defined handlers plus a
 * dedicated manager triggering a stop event at entDate
 */
protected CombinedEventsDetectorsManager addEndDateChecker(final AbsoluteDate startDate,
        final AbsoluteDate endDate, final CombinedEventsDetectorsManager manager) {
    final CombinedEventsDetectorsManager newManager = new CombinedEventsDetectorsManager();
    for (final EventDetector detector : manager.getEventsDetectors()) {
        newManager.addEventDetector(detector);
    }
    final double dt = endDate.durationFrom(startDate);
    newManager.addEventDetector(new EndDateDetector(endDate, Double.POSITIVE_INFINITY, Math.ulp(dt)));
    return newManager;
}

From source file:sly.speakrecognizer.test.math.MultivariateNormalMixtureExpectationMaximizationFitterTest.java

@Test
public void testInitialMixture() {
    // Testing initial mixture estimated from data
    double[] correctWeights = new double[] { 0.5, 0.5 };

    MultivariateNormalDistribution[] correctMVNs = new MultivariateNormalDistribution[2];

    correctMVNs[0] = new MultivariateNormalDistribution(
            new double[] { -0.0021722935000328823, 3.5432892936887908 }, new double[][] {
                    { 4.537422569229048, 3.5266152281729304 }, { 3.5266152281729304, 6.175448814169779 } });
    correctMVNs[1] = new MultivariateNormalDistribution(new double[] { 5.090902706507635, 8.68540656355283 },
            new double[][] { { 2.886778573963039, 1.5257474543463154 },
                    { 1.5257474543463154, 3.3794567673616918 } });

    final MixtureMultivariateNormalDistribution initialMix = MultivariateNormalMixtureExpectationMaximization
            .estimate(getTestSamples(), 2);

    int i = 0;//from www .  j  av  a 2 s  . co  m
    for (Pair<Double, MultivariateNormalDistribution> component : initialMix.getComponents()) {
        Assert.assertEquals(correctWeights[i], component.getFirst(), Math.ulp(1d));

        assertMultivariateNormalDistribution(correctMVNs[i], component.getSecond(), 0);
        //===========================

        i++;
    }
}

From source file:sly.speakrecognizer.test.math.MultivariateNormalMixtureExpectationMaximizationFitterTest.java

@Test
public void testFit() {
    // Test that the loglikelihood, weights, and models are determined and
    // fitted correctly
    double[][] data = getTestSamples();
    double correctLogLikelihood = -4.292431006791994;
    double[] correctWeights = new double[] { 0.2962324189652912, 0.7037675810347089 };
    MultivariateNormalDistribution[] correctMVNs = new MultivariateNormalDistribution[2];
    correctMVNs[0] = new MultivariateNormalDistribution(
            new double[] { -1.4213112715121132, 1.6924690505757753 }, new double[][] {
                    { 1.739356907285747, -0.5867644251487614 }, { -0.5867644251487614, 1.0232932029324642 } });

    correctMVNs[1] = new MultivariateNormalDistribution(new double[] { 4.213612224374709, 7.975621325853645 },
            new double[][] { { 4.245384898007161, 2.5797798966382155 },
                    { 2.5797798966382155, 3.9200272522448367 } });
    //=========================================
    MultivariateNormalMixtureExpectationMaximization fitter = new MultivariateNormalMixtureExpectationMaximization(
            data);/*w w  w  . j ava 2s  .c  o m*/
    MixtureMultivariateNormalDistribution initialMix = MultivariateNormalMixtureExpectationMaximization
            .estimate(data, 2);
    fitter.fit(initialMix);
    MixtureMultivariateNormalDistribution fittedMix = fitter.getFittedModel();
    printMMND(fittedMix);
    List<Pair<Double, MultivariateNormalDistribution>> components = fittedMix.getComponents();

    Assert.assertEquals(correctLogLikelihood, fitter.getLogLikelihood(), Math.ulp(1d));

    int i = 0;
    for (Pair<Double, MultivariateNormalDistribution> component : components) {
        double weight = component.getFirst();
        MultivariateNormalDistribution mvn = component.getSecond();
        Assert.assertEquals(correctWeights[i], weight, Math.ulp(1d));
        assertMultivariateNormalDistribution(correctMVNs[i], mvn, 0);
        i++;
    }
}