Example usage for java.lang Math signum

List of usage examples for java.lang Math signum

Introduction

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

Prototype

public static float signum(float f) 

Source Link

Document

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

Usage

From source file:org.phenotips.similarity.internal.SolrSimilarPatientsFinder.java

private List<PatientSimilarityView> find(Patient referencePatient, boolean prototypes) {
    //logger.error("Searching for patients using access level: {}", this.accessLevelThreshold.getName());
    SolrQuery query = generateQuery(referencePatient, prototypes);
    SolrDocumentList docs = search(query);
    List<PatientSimilarityView> results = new ArrayList<PatientSimilarityView>(docs.size());
    for (SolrDocument doc : docs) {
        String name = (String) doc.getFieldValue("document");
        Patient matchPatient = this.patients.getPatientById(name);
        if (matchPatient == null) {
            // Leftover patient in the index, should be removed
            continue;
        }/*from  w ww . j a  v a  2 s .c  o m*/
        PatientSimilarityView result = this.factory.makeSimilarPatient(matchPatient, referencePatient);
        //logger.error("Found match: found {}, score: {}, accessLevel: {}, accessCompare: {}",
        //             name, result.getScore(), result.getAccess().getName(),
        //             this.accessLevelThreshold.compareTo(result.getAccess()));
        if (this.accessLevelThreshold.compareTo(result.getAccess()) <= 0 && result.getScore() > 0) {
            //logger.error("added match");
            results.add(result);
        }
    }

    Collections.sort(results, new Comparator<PatientSimilarityView>() {
        @Override
        public int compare(PatientSimilarityView o1, PatientSimilarityView o2) {
            return (int) Math.signum(o2.getScore() - o1.getScore());
        }
    });
    return results;
}

From source file:net.sf.jasperreports.functions.standard.MathFunctions.java

/**
 * Returns the sign of a number.//w w  w.ja va2s.  c o  m
 */
@Function("SIGN")
@FunctionParameters({ @FunctionParameter("number") })
public static Integer SIGN(Number number) {
    if (number == null) {
        logNullArgument();
        return null;
    } else {
        return (int) Math.signum(number.doubleValue());
    }
}

From source file:be.ugent.maf.cellmissy.analysis.singlecell.processing.impl.interpolation.TrackHermiteInterpolator.java

/**
 *
 * @param x/*  www  . j  a  va2 s  .c  o  m*/
 * @param y
 * @return
 */
private double[] internalPointsDerivative(double[] x, double[] y) {
    int L = y.length;
    double internalPointsDerivative[] = new double[L];
    for (int k = 1; k < L - 1; k++) {
        // compute the slopes at internal points x[k]
        double hk = x[k + 1] - x[k];
        double hk_previous = x[k] - x[k - 1];
        // the first divided difference is:
        double deltak = (y[k + 1] - y[k]) / hk;
        double deltak_previous = (y[k] - y[k - 1]) / hk_previous;
        if (Math.signum(deltak) != Math.signum(deltak_previous) | Math.signum(deltak) == 0
                | Math.signum(deltak_previous) == 0) {
            internalPointsDerivative[k - 1] = 0;
        } else {
            // compute the weighted harmonic mean
            double w1 = 2 * hk + hk_previous;
            double w2 = hk + 2 * hk_previous;
            internalPointsDerivative[k - 1] = (deltak * deltak_previous) * (w1 + w2)
                    / (w1 * deltak + w2 * deltak_previous);
        }
    }

    return internalPointsDerivative;
}

From source file:com.opengamma.analytics.financial.interestrate.swaption.provider.SwaptionPhysicalFixedIborLMMDDMethod.java

/**
 * Computes the present value of the Physical delivery swaption.
 * @param swaption The swaption./*  w  w  w . jav  a 2 s  .  c om*/
 * @param lmmData The LMM and multi-curves provider.
 * @return The present value.
 */
public MultipleCurrencyAmount presentValue(final SwaptionPhysicalFixedIbor swaption,
        final LiborMarketModelDisplacedDiffusionProviderInterface lmmData) {
    ArgumentChecker.notNull(swaption, "Swaption");
    ArgumentChecker.notNull(lmmData, "LMM provider");
    final Currency ccy = swaption.getCurrency();
    final MulticurveProviderInterface multicurves = lmmData.getMulticurveProvider();
    final LiborMarketModelDisplacedDiffusionParameters parameters = lmmData.getLMMParameters();
    // 1. Swaption CFE preparation
    final AnnuityPaymentFixed cfe = swaption.getUnderlyingSwap().accept(CFEC, multicurves);
    final int nbCFInit = cfe.getNumberOfPayments();
    final double multFact = Math.signum(cfe.getNthPayment(0).getAmount());
    final boolean isCall = (cfe.getNthPayment(0).getAmount() < 0);
    final double[] cftInit = new double[nbCFInit];
    final double[] cfaInit = new double[nbCFInit];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cftInit[loopcf] = cfe.getNthPayment(loopcf).getPaymentTime();
        cfaInit[loopcf] = cfe.getNthPayment(loopcf).getAmount() * -multFact;
    }
    final double timeToExpiry = swaption.getTimeToExpiry();
    // 2. Model data
    final int nbFactor = parameters.getNbFactor();
    final double[][] volLMM = parameters.getVolatility();
    final double[] timeLMM = parameters.getIborTime();
    // 3. Link cfe dates to lmm
    final int[] indCFDate = new int[nbCFInit];
    int indStart = nbCFInit - 1;
    int indEnd = 0;
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        indCFDate[loopcf] = Arrays.binarySearch(timeLMM, cftInit[loopcf]);
        if (indCFDate[loopcf] < 0) {
            if (timeLMM[-indCFDate[loopcf] - 1] - cftInit[loopcf] < TIME_TOLERANCE) {
                indCFDate[loopcf] = -indCFDate[loopcf] - 1;
            } else {
                if (cftInit[loopcf] - timeLMM[-indCFDate[loopcf] - 2] < TIME_TOLERANCE) {
                    indCFDate[loopcf] = -indCFDate[loopcf] - 2;
                } else {
                    Validate.isTrue(true, "Instrument time incompatible with LMM parametrisation");
                }
            }
        }
        if (indCFDate[loopcf] < indStart) {
            indStart = indCFDate[loopcf];
        }
        if (indCFDate[loopcf] > indEnd) {
            indEnd = indCFDate[loopcf];
        }
    }
    final int nbCF = indEnd - indStart + 1;
    final double[] cfa = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfa[indCFDate[loopcf] - indStart] = cfaInit[loopcf];
    }
    final double[] cft = new double[nbCF];
    System.arraycopy(timeLMM, indStart, cft, 0, nbCF);

    final double[] dfLMM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dfLMM[loopcf] = multicurves.getDiscountFactor(ccy, cft[loopcf]);
    }
    final double[][] gammaLMM = new double[nbCF - 1][nbFactor];
    final double[] deltaLMM = new double[nbCF - 1];
    System.arraycopy(parameters.getAccrualFactor(), indStart, deltaLMM, 0, nbCF - 1);
    final double[] aLMM = new double[nbCF - 1];
    System.arraycopy(parameters.getDisplacement(), indStart, aLMM, 0, nbCF - 1);
    final double[] liborLMM = new double[nbCF - 1];
    final double amr = parameters.getMeanReversion();
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        gammaLMM[loopcf] = volLMM[indStart + loopcf];
        liborLMM[loopcf] = (dfLMM[loopcf] / dfLMM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    // TODO: 4. cfe modification (for roller coasters)
    final double[] cfaMod = new double[nbCF + 1];
    final double cfaMod0 = cfa[0];
    cfaMod[0] = cfaMod0; // modified strike
    cfaMod[1] = 0.0;
    System.arraycopy(cfa, 1, cfaMod, 2, nbCF - 1);
    // 5. Pricing algorithm
    final double[] p0 = new double[nbCF];
    final double[] dP = new double[nbCF];
    double b0 = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        p0[loopcf] = dfLMM[loopcf] / dfLMM[0];
        dP[loopcf] = cfaMod[loopcf + 1] * p0[loopcf];
        b0 += dP[loopcf];
    }
    final double bK = -cfaMod0;
    final double bM = (b0 + bK) / 2.0d;
    final double meanReversionImpact = Math.abs(amr) < 1.0E-6 ? timeToExpiry
            : (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr); // To handle 0 mean reversion.
    final double[] rate0Ratio = new double[nbCF - 1];
    final double[][] mu0 = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rate0Ratio[loopcf] = (liborLMM[loopcf] + aLMM[loopcf]) / (liborLMM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        mu0[0][loopfact] = rate0Ratio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0[loopcf][loopfact] = mu0[loopcf - 1][loopfact] + rate0Ratio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    final double[] tau = new double[nbCF];
    final double[] tau2 = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            tau2[loopcf + 1] += mu0[loopcf][loopfact] * mu0[loopcf][loopfact];
        }
        tau2[loopcf + 1] = tau2[loopcf + 1] * meanReversionImpact;
        tau[loopcf + 1] = Math.sqrt(tau2[loopcf + 1]);
    }
    double sumNum = -bM;
    double sumDen = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        sumNum += dP[loopcf] - dP[loopcf] * tau2[loopcf] / 2.0;
        sumDen += dP[loopcf] * tau[loopcf];
    }
    final double xBar = sumNum / sumDen;
    final double[] pM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pM[loopcf] = p0[loopcf] * (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0);
    }
    final double[] liborM = new double[nbCF - 1];
    final double[] alphaM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborM[loopcf] = (pM[loopcf] / pM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        alphaM[loopcf] = cfaMod[loopcf + 1] * pM[loopcf] / bM;
    }
    final double[] rateMRatio = new double[nbCF - 1];
    final double[][] muM = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rateMRatio[loopcf] = (liborM[loopcf] + aLMM[loopcf]) / (liborM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        muM[0][loopfact] = rateMRatio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muM[loopcf][loopfact] = muM[loopcf - 1][loopfact] + rateMRatio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    double normSigmaM = 0;
    final double[] sigmaM = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            sigmaM[loopfact] += alphaM[loopcf + 1] * muM[loopcf][loopfact];
        }
        normSigmaM += sigmaM[loopfact] * sigmaM[loopfact];
    }
    final double impliedBlackVol = Math.sqrt(normSigmaM * meanReversionImpact);
    final EuropeanVanillaOption option = new EuropeanVanillaOption(bK, 1, isCall);
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(b0, 1.0, impliedBlackVol);
    final Function1D<BlackFunctionData, Double> func = blackFunction.getPriceFunction(option);
    final double pv = dfLMM[0] * func.evaluate(dataBlack);
    return MultipleCurrencyAmount.of(swaption.getUnderlyingSwap().getFirstLeg().getCurrency(),
            pv * (swaption.isLong() ? 1.0 : -1.0));
}

From source file:org.apache.pulsar.io.file.FileSourceConfig.java

public void validate() {
    if (StringUtils.isBlank(inputDirectory)) {
        throw new IllegalArgumentException("Required property not set.");
    } else if (Files.notExists(Paths.get(inputDirectory), LinkOption.NOFOLLOW_LINKS)) {
        throw new IllegalArgumentException("Specified input directory does not exist");
    } else if (!Files.isReadable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("Specified input directory is not readable");
    } else if (Optional.ofNullable(keepFile).orElse(false) && !Files.isWritable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("You have requested the consumed files to be deleted, but the "
                + "source directory is not writeable.");
    }// w  w w  . j  a v a  2  s  . co  m

    if (StringUtils.isNotBlank(fileFilter)) {
        try {
            Pattern.compile(fileFilter);
        } catch (final PatternSyntaxException psEx) {
            throw new IllegalArgumentException("Invalid Regex pattern provided for fileFilter");
        }
    }

    if (minimumFileAge != null && Math.signum(minimumFileAge) < 0) {
        throw new IllegalArgumentException("The property minimumFileAge must be non-negative");
    }

    if (maximumFileAge != null && Math.signum(maximumFileAge) < 0) {
        throw new IllegalArgumentException("The property maximumFileAge must be non-negative");
    }

    if (minimumSize != null && Math.signum(minimumSize) < 0) {
        throw new IllegalArgumentException("The property minimumSize must be non-negative");
    }

    if (maximumSize != null && Math.signum(maximumSize) < 0) {
        throw new IllegalArgumentException("The property maximumSize must be non-negative");
    }

    if (pollingInterval != null && pollingInterval <= 0) {
        throw new IllegalArgumentException("The property pollingInterval must be greater than zero");
    }

    if (numWorkers != null && numWorkers <= 0) {
        throw new IllegalArgumentException("The property numWorkers must be greater than zero");
    }
}

From source file:org.omnaest.utils.operation.foreach.Range.java

/**
 * Allows to specify a {@link Range} with a given {@link String} expression.<br>
 * <br>/*from  w w w . j a  va 2  s . c o m*/
 * The expression format is:<br>
 * 
 * <pre>
 * new Range( &quot;1-5&quot; ); //results in 1,2,3,4,5
 * new Range( &quot;1-5:2&quot; ); //results in 1,3,5
 * new Range( &quot;123&quot; ); //result in only a single value
 * 
 * </pre>
 * 
 * @see Range
 * @param rangeExpression
 */
public Range(String rangeExpression) {
    super();

    Assert.isNotNull(rangeExpression);

    ReplacementResult replacementResult = new StringReplacer("\\:([0-9]*)$").setGroup(1)
            .findAndRemoveFirst(rangeExpression);
    final boolean hasDeclaredStep = replacementResult.hasMatchingTokens();
    if (hasDeclaredStep) {
        String[] matchingTokens = replacementResult.getMatchingTokens();
        if (matchingTokens != null && matchingTokens.length == 1) {
            final String stepString = matchingTokens[0];
            Assert.isTrue(StringUtils.isNumeric(stepString), "Step must be numerical but was " + stepString);
            this.step = NumberUtils.toLong(stepString, DEFAULT_STEP);
        }
    }
    rangeExpression = replacementResult.getOutput();

    String[] tokens = rangeExpression.split("-");
    Assert.isTrue(tokens.length == 2 || tokens.length == 1);
    if (tokens.length == 2) {
        Assert.isTrue(StringUtils.isNumeric(tokens[0]), "Range start must be numerical but was " + tokens[0]);
        Assert.isTrue(StringUtils.isNumeric(tokens[1]), "Range start must be numerical but was " + tokens[1]);

        this.numberFrom = Long.valueOf(tokens[0]);
        this.numberTo = Long.valueOf(tokens[1]);
    } else if (tokens.length == 1) {
        Assert.isTrue(StringUtils.isNumeric(tokens[0]),
                "Range start and end must be numerical but was " + tokens[0]);

        this.numberFrom = this.numberTo = Long.valueOf(tokens[0]);
    }

    if (!hasDeclaredStep) {
        this.step = determineDefaultStep(this.numberFrom, this.numberTo);
    }
    Assert.isTrue(
            this.numberTo == this.numberFrom
                    || Math.signum(this.numberTo - this.numberFrom) == Math.signum(this.step),
            "The given end number cannot be reached by the given start number and step " + this);
}

From source file:org.apache.helix.tools.ZkGrep.java

/**
 * get files under dir in order of last modified time
 * @param dir//from   w  w  w  .j  a  va 2s  . com
 * @param pattern
 * @return
 */
static File[] getSortedFiles(String dirPath, final String pattern) {
    File dir = new File(dirPath);
    File[] files = dir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File file) {
            return file.isFile() && (file.getName().indexOf(pattern) != -1);
        }
    });

    Arrays.sort(files, new Comparator<File>() {

        @Override
        public int compare(File o1, File o2) {
            int sign = (int) Math.signum(o1.lastModified() - o2.lastModified());
            return sign;
        }

    });
    return files;
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionMath.java

/**
 * data provider generator for single-value tests
 * @return data/*from   w ww .j  a v  a  2s . co m*/
 */
@DataProvider
public static Object[] singlevaluegenerate() {
    return Stream.concat(

            singlevaluetestcase(

                    Stream.of(2.5, 9.1, 111.7, 889.9),

                    Stream.of(CNextPrime.class),

                    (i) -> (double) Primes.nextPrime(i.intValue())),

            singlevaluetestcase(

                    Stream.of(-2, -6, 4, -1, -5, 3, 49, 30, 6, 5, 1.3, 2.8, 9.7, 1, 8, 180, Math.PI),

                    Stream.of(CAbs.class, CACos.class, CASin.class, CATan.class, CCeil.class, CCos.class,
                            CCosh.class, CDegrees.class, CExp.class, CIsPrime.class, CLog.class, CLog10.class,
                            CFloor.class, CRadians.class, CRound.class, CSignum.class, CSin.class, CSinh.class,
                            CSqrt.class, CTan.class, CTanh.class),

                    (i) -> Math.abs(i.doubleValue()), (i) -> Math.acos(i.doubleValue()),
                    (i) -> Math.asin(i.doubleValue()), (i) -> Math.atan(i.doubleValue()),
                    (i) -> Math.ceil(i.doubleValue()), (i) -> Math.cos(i.doubleValue()),
                    (i) -> Math.cosh(i.doubleValue()), (i) -> Math.toDegrees(i.doubleValue()),
                    (i) -> Math.exp(i.doubleValue()), (i) -> Primes.isPrime(i.intValue()),
                    (i) -> Math.log(i.doubleValue()), (i) -> Math.log10(i.doubleValue()),
                    (i) -> Math.floor(i.doubleValue()), (i) -> Math.toRadians(i.doubleValue()),
                    (i) -> Math.round(i.doubleValue()), (i) -> Math.signum(i.doubleValue()),
                    (i) -> Math.sin(i.doubleValue()), (i) -> Math.sinh(i.doubleValue()),
                    (i) -> Math.sqrt(i.doubleValue()), (i) -> Math.tan(i.doubleValue()),
                    (i) -> Math.tanh(i.doubleValue()))

    ).toArray();
}

From source file:org.knowrob.vis.model.util.algorithm.ACCUM.java

/**
 * Calculate hue and saturation for curvature properties.
 * //from   ww  w  .  j  a  v  a  2 s.  com
 * @param curvatures
 *            maps curvatures to vertices
 * @param smoothSigma
 *            sigma value for smoothing the curvature. Set to 0 to disable smoothing.
 * @param m
 *            model needed to calculate hue saturation scale
 */
public static void setCurvatureHueSaturation(HashMap<Vertex, Curvature> curvatures, Model m,
        float smoothSigma) {
    if (smoothSigma > 0.0f) {
        float scaledSigma = smoothSigma * m.feature_size();
        diffuse_curv(m, curvatures, scaledSigma);
    }

    float cscale = 120.0f * typical_scale(curvatures, m);
    cscale = cscale * cscale;
    int nv = m.getVertices().size();
    for (int i = 0; i < nv; i++) {
        Curvature c = curvatures.get(m.getVertices().get(i));
        float H = 0.5f * (c.getCurvatureMax() + c.getCurvatureMin());
        // mean curvature -> don't set the mean curvature here as we want only the initial one to be stored and this method is public
        float K = c.getCurvatureMax() * c.getCurvatureMin();
        // Gaussian curvature -> don't set the Gaussian curvature here as we want only the initial one to be stored and this method is public
        float h = (float) (4.0f / 3.0f * Math.abs(Math.atan2(H * H - K, H * H * Math.signum(H))));
        float s = (float) ((2 / Math.PI) * Math.atan((2.0f * H * H - K) * cscale));
        c.setHue(h);
        c.setSaturation(s);
    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.SequentialProjectionHashLearner.java

@Override
public long hash(final RealVector x) {
    assert (K <= 64);
    long h = 0L;//from  w w  w  .  java2  s  . c om
    long shift = 1;
    final RealVector centered = x.subtract(b);
    for (int k = 0; k < K; ++k) {
        final double hk = Math.signum(W.get(k).dotProduct(centered));
        if (hk > 0) {
            h |= shift;
        }
        shift <<= 1;
    }
    return h;
}