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:bdsup2sub.cli.CommandLineParser.java

public void printHelp() {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator() {
        @Override/*from  ww  w.  j av a 2 s  .  com*/
        public int compare(Object o1, Object o2) {
            Option opt1 = (Option) o1;
            Option opt2 = (Option) o2;

            int opt1Index = OPTION_ORDER.indexOf(opt1.getOpt());
            int opt2Index = OPTION_ORDER.indexOf(opt2.getOpt());

            return (int) Math.signum(opt1Index - opt2Index);
        }
    });
    formatter.setWidth(79);
    String command = System.getProperty("wrapper") == null ? "java -jar BDSup2Sub" : "bdsup2sub";
    formatter.printHelp(command + " [options] -o <output> <input>", options);
}

From source file:com.android.launcher3.ItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected    The ViewHolder to drag or swipe. Can be null if you want to cancel the
 *                    current action/* w w w.  ja  v a  2  s .  co m*/
 * @param actionState The type of action
 */
void select(android.support.v7.widget.RecyclerView.ViewHolder selected, int actionState) {
    if (selected == mSelected && actionState == mActionState) {
        return;
    }
    mDragScrollStartTimeInMs = Long.MIN_VALUE;
    final int prevActionState = mActionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    mActionState = actionState;
    if (actionState == ACTION_STATE_DRAG) {
        // we remove after animation is complete. this means we only elevate the last drag
        // child but that should perform good enough as it is very hard to start dragging a
        // new child before the previous one settles.
        mOverdrawChild = selected.itemView;
        addChildDrawingOrderCallback();
    }
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    if (mSelected != null) {
        final android.support.v7.widget.RecyclerView.ViewHolder prevSelected = mSelected;
        if (prevSelected.itemView.getParent() != null) {
            final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 : swipeIfNecessary(prevSelected);
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            int animationType;
            switch (swipeDir) {
            case LEFT:
            case RIGHT:
            case START:
            case END:
                targetTranslateY = 0;
                targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
                break;
            case UP:
            case DOWN:
                targetTranslateX = 0;
                targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
                break;
            default:
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            if (prevActionState == ACTION_STATE_DRAG) {
                animationType = ANIMATION_TYPE_DRAG;
            } else if (swipeDir > 0) {
                animationType = ANIMATION_TYPE_SWIPE_SUCCESS;
            } else {
                animationType = ANIMATION_TYPE_SWIPE_CANCEL;
            }
            getSelectedDxDy(mTmpPosition);
            final float currentTranslateX = mTmpPosition[0];
            final float currentTranslateY = mTmpPosition[1];
            final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, prevActionState,
                    currentTranslateX, currentTranslateY, targetTranslateX, targetTranslateY) {
                @Override
                public void onAnimationEnd(ValueAnimatorCompat animation) {
                    super.onAnimationEnd(animation);
                    if (this.mOverridden) {
                        return;
                    }
                    if (swipeDir <= 0) {
                        // this is a drag or failed swipe. recover immediately
                        mCallback.clearView(mRecyclerView, prevSelected);
                        // full cleanup will happen on onDrawOver
                    } else {
                        // wait until remove animation is complete.
                        mPendingCleanup.add(prevSelected.itemView);
                        mIsPendingCleanup = true;
                        if (swipeDir > 0) {
                            // Animation might be ended by other animators during a layout.
                            // We defer callback to avoid editing adapter during a layout.
                            postDispatchSwipe(this, swipeDir);
                        }
                    }
                    // removed from the list after it is drawn for the last time
                    if (mOverdrawChild == prevSelected.itemView) {
                        removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
                    }
                }
            };
            final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            mRecoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
            mCallback.clearView(mRecyclerView, prevSelected);
        }
        mSelected = null;
    }
    if (selected != null) {
        mSelectedFlags = (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected)
                & actionStateMask) >> (mActionState * DIRECTION_FLAG_COUNT);
        mSelectedStartX = selected.itemView.getLeft();
        mSelectedStartY = selected.itemView.getTop();
        mSelected = selected;

        if (actionState == ACTION_STATE_DRAG) {
            mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    final ViewParent rvParent = mRecyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
    }
    if (!preventLayout) {
        mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    mCallback.onSelectedChanged(mSelected, mActionState);
    mRecyclerView.invalidate();
}

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

/**
 * Computes the present value curve sensitivity of the Physical delivery swaption.
 * @param swaption The swaption.//  ww w . j av a 2 s  . c om
 * @param lmmBundle The LMM parameters and the curves.
 * @return The present value.
 */
public InterestRateCurveSensitivity presentValueCurveSensitivity(final SwaptionPhysicalFixedIbor swaption,
        final LiborMarketModelDisplacedDiffusionDataBundle lmmBundle) {
    // 1. Swaption CFE preparation
    AnnuityPaymentFixed cfe = CFEC.visit(swaption.getUnderlyingSwap(), lmmBundle);
    YieldAndDiscountCurve dsc = lmmBundle.getCurve(cfe.getDiscountCurve());
    int nbCFInit = cfe.getNumberOfPayments();
    double multFact = Math.signum(cfe.getNthPayment(0).getAmount());
    boolean isCall = (cfe.getNthPayment(0).getAmount() < 0);
    double[] cftInit = new double[nbCFInit];
    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;
    }
    double timeToExpiry = swaption.getTimeToExpiry();
    // 2. Model data
    int nbFactor = lmmBundle.getLmmParameter().getNbFactor();
    double[][] volLMM = lmmBundle.getLmmParameter().getVolatility();
    double[] timeLMM = lmmBundle.getLmmParameter().getIborTime();
    // 3. Link cfe dates to lmm
    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");
                }
            }
        }
        if (indCFDate[loopcf] < indStart) {
            indStart = indCFDate[loopcf];
        }
        if (indCFDate[loopcf] > indEnd) {
            indEnd = indCFDate[loopcf];
        }
    }
    int nbCF = indEnd - indStart + 1;
    double[] cfa = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfa[indCFDate[loopcf] - indStart] = cfaInit[loopcf];
    }
    double[] cft = new double[nbCF];
    System.arraycopy(timeLMM, indStart, cft, 0, nbCF);
    double[] dfLMM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dfLMM[loopcf] = dsc.getDiscountFactor(cft[loopcf]);
    }
    double[][] gammaLMM = new double[nbCF - 1][nbFactor];
    double[] deltaLMM = new double[nbCF - 1];
    System.arraycopy(lmmBundle.getLmmParameter().getAccrualFactor(), indStart, deltaLMM, 0, nbCF - 1);
    double[] aLMM = new double[nbCF - 1];
    System.arraycopy(lmmBundle.getLmmParameter().getDisplacement(), indStart, aLMM, 0, nbCF - 1);
    double[] liborLMM = new double[nbCF - 1];
    double amr = lmmBundle.getLmmParameter().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];
    }
    double[] cfaMod = new double[nbCF + 1];
    double cfaMod0 = cfa[0];
    cfaMod[0] = cfaMod0; // modified strike
    cfaMod[1] = 0.0; // TODO: 4. cfe modification (for roller coasters)
    System.arraycopy(cfa, 1, cfaMod, 2, nbCF - 1);
    // 5. Pricing algorithm
    double[] p0 = new double[nbCF];
    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];
    }
    double bK = -cfaMod[0];
    double bM = (b0 + bK) / 2.0d;
    double[] rate0Ratio = new double[nbCF - 1];
    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];
        }
    }
    double meanReversionImpact = (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr);
    double[] tau = new double[nbCF];
    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];
    }
    double xBar = sumNum / sumDen;
    double[] pM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pM[loopcf] = p0[loopcf] * (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0);
    }
    double[] liborM = new double[nbCF - 1];
    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;
    }
    double[] rateMRatio = new double[nbCF - 1];
    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;
    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];
    }
    double impliedBlackVol = Math.sqrt(normSigmaM * meanReversionImpact);
    EuropeanVanillaOption option = new EuropeanVanillaOption(bK, 1, isCall);
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(b0, 1.0, impliedBlackVol);
    double[] blkAdjoint = blackFunction.getPriceAdjoint(option, dataBlack);
    // Backward sweep
    double pvBar = 1.0;
    double impliedBlackVolBar = dfLMM[0] * blkAdjoint[2] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    double normSigmaMBar = meanReversionImpact / (2.0 * impliedBlackVol) * impliedBlackVolBar;
    double[] sigmaMBar = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        sigmaMBar[loopfact] = 2 * sigmaM[loopfact] * normSigmaMBar;
    }
    double[][] muMBar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] = alphaM[loopcf + 1] * sigmaMBar[loopfact];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] += muMBar[loopcf + 1][loopfact];
        }
    }
    double[] rateMRatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rateMRatioBar[loopcf] += gammaLMM[loopcf][loopfact] * muMBar[loopcf][loopfact];
        }
    }
    double[] alphaMBar = new double[nbCF];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            alphaMBar[loopcf + 1] += muM[loopcf][loopfact] * sigmaMBar[loopfact];
        }
    }
    double[] liborMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborMBar[loopcf] = ((liborM[loopcf] + 1 / deltaLMM[loopcf]) - (liborM[loopcf] + aLMM[loopcf]))
                / ((liborM[loopcf] + 1 / deltaLMM[loopcf]) * (liborM[loopcf] + 1 / deltaLMM[loopcf]))
                * rateMRatioBar[loopcf];
    }
    double[] pMBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        pMBar[loopcf] += 1.0 / pM[loopcf + 1] / deltaLMM[loopcf] * liborMBar[loopcf];
        pMBar[loopcf + 1] += -pM[loopcf] / (pM[loopcf + 1] * pM[loopcf + 1]) / deltaLMM[loopcf]
                * liborMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pMBar[loopcf] += cfaMod[loopcf + 1] / bM * alphaMBar[loopcf];
    }
    double xBarBar = 0.0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        xBarBar += -p0[loopcf] * tau[loopcf] * pMBar[loopcf];
    }
    double sumNumBar = 1.0 / sumDen * xBarBar;
    double sumDenBar = -sumNum / (sumDen * sumDen) * xBarBar;
    double[] tauBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] = -p0[loopcf] * xBar * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] += dP[loopcf] * sumDenBar;
    }
    double[] tau2Bar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] = -p0[loopcf] / 2.0 * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] += -dP[loopcf] / 2.0 * sumNumBar;
    }
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        tau2Bar[loopcf + 1] += 1.0 / tau[loopcf + 1] / 2.0 * tauBar[loopcf + 1];
    }
    double[][] mu0Bar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] = 2.0 * mu0[loopcf][loopfact] * meanReversionImpact * tau2Bar[loopcf + 1];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] += mu0Bar[loopcf + 1][loopfact];
        }
    }
    double[] rate0RatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rate0RatioBar[loopcf] += gammaLMM[loopcf][loopfact] * mu0Bar[loopcf][loopfact];
        }
    }
    double bMBar = -sumNumBar;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        bMBar += -cfaMod[loopcf + 1] * pM[loopcf] / (bM * bM) * alphaMBar[loopcf];
    }
    double bKBar = bMBar / 2.0;
    bKBar += dfLMM[0] * blkAdjoint[3] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    double b0Bar = bMBar / 2.0;
    b0Bar += dfLMM[0] * blkAdjoint[1] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    double[] dPBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dPBar[loopcf] = b0Bar + tau[loopcf] * sumDenBar + (1.0 - tau2[loopcf] / 2.0) * sumNumBar;
    }
    double[] p0Bar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        p0Bar[loopcf] = cfaMod[loopcf + 1] * dPBar[loopcf]
                + (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0) * pMBar[loopcf];
    }

    double[] cfaModBar = new double[nbCF + 1];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        cfaModBar[loopcf + 1] = p0[loopcf] * dPBar[loopcf] + pM[loopcf] / bM * alphaMBar[loopcf];
    }
    cfaModBar[0] += -bKBar;

    double[] liborLMMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborLMMBar[loopcf] = (1.0 / (liborLMM[loopcf] + 1 / deltaLMM[loopcf])
                - (liborLMM[loopcf] + aLMM[loopcf]) / ((liborLMM[loopcf] + 1 / deltaLMM[loopcf])
                        * (liborLMM[loopcf] + 1 / deltaLMM[loopcf])))
                * rate0RatioBar[loopcf];
    }
    double[] dfLMMBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        dfLMMBar[loopcf] += (1.0 / dfLMM[loopcf + 1]) / deltaLMM[loopcf] * liborLMMBar[loopcf];
        dfLMMBar[loopcf + 1] += -dfLMM[loopcf] / (dfLMM[loopcf + 1] * dfLMM[loopcf + 1]) / deltaLMM[loopcf]
                * liborLMMBar[loopcf];
    }
    for (int loopcf = 1; loopcf < nbCF; loopcf++) {
        dfLMMBar[loopcf] += 1.0 / dfLMM[0] * p0Bar[loopcf];
        dfLMMBar[0] += -dfLMM[loopcf] / (dfLMM[0] * dfLMM[0]) * p0Bar[loopcf];
    }
    dfLMMBar[0] += blkAdjoint[0] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    double[] cfaBar = new double[nbCF];
    cfaBar[0] = cfaModBar[0];
    System.arraycopy(cfaModBar, 2, cfaBar, 1, nbCF - 1);
    double[] cfaInitBar = new double[nbCFInit];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfaInitBar[loopcf] = cfaBar[indCFDate[loopcf] - indStart];
    }

    final List<DoublesPair> listDfSensi = new ArrayList<DoublesPair>();
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        DoublesPair dfSensi = new DoublesPair(cft[loopcf], -cft[loopcf] * dfLMM[loopcf] * dfLMMBar[loopcf]);
        listDfSensi.add(dfSensi);
    }
    final Map<String, List<DoublesPair>> pvsDF = new HashMap<String, List<DoublesPair>>();
    pvsDF.put(cfe.getDiscountCurve(), listDfSensi);
    InterestRateCurveSensitivity sensitivity = new InterestRateCurveSensitivity(pvsDF);
    Map<Double, InterestRateCurveSensitivity> cfeCurveSensi = CFECSC.visit(swaption.getUnderlyingSwap(),
            lmmBundle);
    for (int loopcf = 0; loopcf < cfe.getNumberOfPayments(); loopcf++) {
        InterestRateCurveSensitivity sensiCfe = cfeCurveSensi.get(cfe.getNthPayment(loopcf).getPaymentTime());
        if (!(sensiCfe == null)) { // There is some sensitivity to that cfe.
            sensitivity = sensitivity.plus(sensiCfe.multiply(-multFact * cfaInitBar[loopcf]));
        }
    }
    return sensitivity;
}

From source file:gdsc.smlm.ij.plugins.EMGainAnalysis.java

private void plotPMF() {
    if (!showPMFDialog())
        return;/*from  w w  w .ja va  2 s  .  c  om*/

    final int gaussWidth = 5;
    int dummyBias = (int) Math.max(500, gaussWidth * _noise + 1);

    double[] pmf = pdf(0, _photons, _gain, _noise, dummyBias);
    double[] x = Utils.newArray(pmf.length, 0, 1.0);
    double yMax = Maths.max(pmf);

    // Truncate x
    int max = 0;
    double sum = 0;
    double p = 1 - tail;
    while (sum < p && max < pmf.length) {
        sum += pmf[max];
        max++;
    }

    int min = pmf.length;
    sum = 0;
    p = 1 - head;
    while (sum < p && min > 0) {
        min--;
        sum += pmf[min];
    }

    //int min = (int) (dummyBias - gaussWidth * _noise);
    pmf = Arrays.copyOfRange(pmf, min, max);
    x = Arrays.copyOfRange(x, min, max);

    // Get the approximation
    double[] f = new double[x.length];
    PoissonGammaGaussianFunction fun = new PoissonGammaGaussianFunction(1.0 / _gain, _noise);
    double expected = _photons;
    if (offset != 0)
        expected += offset * expected / 100.0;
    expected *= _gain;
    for (int i = 0; i < f.length; i++) {
        // Adjust the x-values to remove the dummy bias
        x[i] -= dummyBias;
        f[i] = fun.likelihood(x[i], expected);
    }
    if (showApproximation)
        yMax = Maths.maxDefault(yMax, f);

    String label = String.format("Gain=%s, noise=%s, photons=%s", Utils.rounded(_gain), Utils.rounded(_noise),
            Utils.rounded(_photons));

    Plot2 plot = new Plot2("PMF", "ADUs", "p");
    plot.setLimits(x[0], x[x.length - 1], 0, yMax);
    plot.setColor(Color.red);
    plot.addPoints(x, pmf, Plot2.LINE);
    if (showApproximation) {
        plot.setColor(Color.blue);
        plot.addPoints(x, f, Plot2.LINE);
    }

    plot.setColor(Color.magenta);
    plot.drawLine(_photons * _gain, 0, _photons * _gain, yMax);
    plot.setColor(Color.black);
    plot.addLabel(0, 0, label);
    PlotWindow win1 = Utils.display("PMF", plot);

    // Plot the difference between the actual and approximation
    double[] delta = new double[f.length];
    for (int i = 0; i < f.length; i++) {
        if (pmf[i] == 0 && f[i] == 0)
            continue;
        if (relativeDelta)
            delta[i] = DoubleEquality.relativeError(f[i], pmf[i]) * Math.signum(f[i] - pmf[i]);
        else
            delta[i] = f[i] - pmf[i];
    }

    Plot2 plot2 = new Plot2("PMF delta", "ADUs", (relativeDelta) ? "Relative delta" : "delta");
    double[] limits = Maths.limits(delta);
    plot2.setLimits(x[0], x[x.length - 1], limits[0], limits[1]);
    plot2.setColor(Color.red);
    plot2.addPoints(x, delta, Plot2.LINE);
    plot2.setColor(Color.magenta);
    plot2.drawLine(_photons * _gain, limits[0], _photons * _gain, limits[1]);
    plot2.setColor(Color.black);
    plot2.addLabel(0, 0, label + ((offset == 0) ? "" : ", expected = " + Utils.rounded(expected / _gain)));
    PlotWindow win2 = Utils.display("PMF delta", plot2);

    if (Utils.isNewWindow()) {
        Point p2 = win2.getLocation();
        p2.y += win1.getHeight();
        win2.setLocation(p2);
    }
}

From source file:com.androzic.Androzic.java

public Route trackToRoute(Track track, float sensitivity) throws IllegalArgumentException {
    Route route = new Route();
    List<Track.TrackPoint> points = track.getAllPoints();
    Track.TrackPoint lrp = points.get(0);
    route.addWaypoint("RWPT0", lrp.latitude, lrp.longitude);

    if (points.size() < 2)
        throw new IllegalArgumentException("Track too short");

    Track.TrackPoint cp = points.get(1);
    Track.TrackPoint lp = lrp;/* w ww  . j  a  v a2 s.  co  m*/
    Track.TrackPoint tp = null;
    int i = 1;
    int prx = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(this).getString(
            getString(R.string.pref_navigation_proximity), getString(R.string.def_navigation_proximity)));
    double proximity = prx * sensitivity;
    double d = 0, t = 0, b, pb = 0, cb = -1, icb = 0, xtk = 0;

    while (i < points.size()) {
        cp = points.get(i);
        d += Geo.distance(lp.latitude, lp.longitude, cp.latitude, cp.longitude);
        b = Geo.bearing(lp.latitude, lp.longitude, cp.latitude, cp.longitude);
        t += Geo.turn(pb, b);
        if (Math.abs(t) >= 360) {
            t = t - 360 * Math.signum(t);
        }
        //Log.d("ANDROZIC", i+","+b+","+t);
        lp = cp;
        pb = b;
        i++;

        // calculate initial track
        if (cb < 0) {
            if (d > proximity) {
                cb = Geo.bearing(lrp.latitude, lrp.longitude, cp.latitude, cp.longitude);
                pb = cb;
                t = 0;
                icb = cb + 180;
                if (icb >= 360)
                    icb -= 360;
                // Log.w("ANDROZIC", "Found vector:" + cb);
            }
            continue;
        }
        // find turn
        if (Math.abs(t) > 10) {
            if (tp == null) {
                tp = cp;
                // Log.w("ANDROZIC", "Found turn: "+i);
                continue;
            }
        } else if (tp != null && xtk < proximity / 10) {
            tp = null;
            xtk = 0;
            // Log.w("ANDROZIC", "Reset turn: "+i);
        }
        // if turn in progress check xtk
        if (tp != null) {
            double xd = Geo.distance(cp.latitude, cp.longitude, tp.latitude, tp.longitude);
            double xb = Geo.bearing(cp.latitude, cp.longitude, tp.latitude, tp.longitude);
            xtk = Geo.xtk(xd, icb, xb);
            // turned at sharp angle
            if (xtk == Double.NEGATIVE_INFINITY)
                xtk = Geo.xtk(xd, cb, xb);
            // Log.w("ANDROZIC", "XTK: "+xtk);
            if (Math.abs(xtk) > proximity * 3) {
                lrp = tp;
                route.addWaypoint("RWPT" + route.length(), lrp.latitude, lrp.longitude);
                cb = Geo.bearing(lrp.latitude, lrp.longitude, cp.latitude, cp.longitude);
                // Log.e("ANDROZIC", "Set WPT: "+(route.length()-1)+","+cb);
                pb = cb;
                t = 0;
                icb = cb + 180;
                if (icb >= 360)
                    icb -= 360;
                tp = null;
                d = 0;
                xtk = 0;
            }
            continue;
        }
        // if still direct but pretty far away add a point
        if (d > proximity * 200) {
            lrp = cp;
            route.addWaypoint("RWPT" + route.length(), lrp.latitude, lrp.longitude);
            // Log.e("ANDROZIC", "Set WPT: "+(route.length()-1));
            d = 0;
        }
    }
    lrp = points.get(i - 1);
    route.addWaypoint("RWPT" + route.length(), lrp.latitude, lrp.longitude);
    route.name = "RT_" + track.name;
    route.show = true;
    return route;
}

From source file:se.llbit.chunky.renderer.scene.Sky.java

public boolean cloudIntersection(Scene scene, Ray ray, Random random) {
    double offsetX = cloudOffset.x;
    double offsetY = cloudOffset.y;
    double offsetZ = cloudOffset.z;
    double inv_size = 1 / cloudSize;
    double cloudBot = offsetY - scene.origin.y;
    double cloudTop = offsetY - scene.origin.y + 5;
    int target = 1;
    double t_offset = 0;
    if (ray.o.y < cloudBot || ray.o.y > cloudTop) {
        if (ray.d.y > 0) {
            t_offset = (cloudBot - ray.o.y) / ray.d.y;
        } else {//from  w w w. j  a v  a2  s  . com
            t_offset = (cloudTop - ray.o.y) / ray.d.y;
        }
        if (t_offset < 0) {
            return false;
        }
        // ray is entering cloud
        if (inCloud((ray.d.x * t_offset + ray.o.x) * inv_size + offsetX,
                (ray.d.z * t_offset + ray.o.z) * inv_size + offsetZ)) {
            ray.n.set(0, -Math.signum(ray.d.y), 0);
            onCloudEnter(ray, t_offset);
            return true;
        }
    } else if (inCloud(ray.o.x * inv_size + offsetX, ray.o.z * inv_size + offsetZ)) {
        target = 0;
    }
    double tExit;
    if (ray.d.y > 0) {
        tExit = (cloudTop - ray.o.y) / ray.d.y - t_offset;
    } else {
        tExit = (cloudBot - ray.o.y) / ray.d.y - t_offset;
    }
    if (ray.t < tExit) {
        tExit = ray.t;
    }
    double x0 = (ray.o.x + ray.d.x * t_offset) * inv_size + offsetX;
    double z0 = (ray.o.z + ray.d.z * t_offset) * inv_size + offsetZ;
    double xp = x0;
    double zp = z0;
    int ix = (int) Math.floor(xp);
    int iz = (int) Math.floor(zp);
    int xmod = (int) Math.signum(ray.d.x), zmod = (int) Math.signum(ray.d.z);
    int xo = (1 + xmod) / 2, zo = (1 + zmod) / 2;
    double dx = Math.abs(ray.d.x) * inv_size;
    double dz = Math.abs(ray.d.z) * inv_size;
    double t = 0;
    int i = 0;
    int nx = 0, nz = 0;
    if (dx > dz) {
        double m = dz / dx;
        double xrem = xmod * (ix + xo - xp);
        double zlimit = xrem * m;
        while (t < tExit) {
            double zrem = zmod * (iz + zo - zp);
            if (zrem < zlimit) {
                iz += zmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = i / dx + zrem / dz;
                    nx = 0;
                    nz = -zmod;
                    break;
                }
                ix += xmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = (i + xrem) / dx;
                    nx = -xmod;
                    nz = 0;
                    break;
                }
            } else {
                ix += xmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = (i + xrem) / dx;
                    nx = -xmod;
                    nz = 0;
                    break;
                }
                if (zrem <= m) {
                    iz += zmod;
                    if (Clouds.getCloud(ix, iz) == target) {
                        t = i / dx + zrem / dz;
                        nx = 0;
                        nz = -zmod;
                        break;
                    }
                }
            }
            t = i / dx;
            i += 1;
            zp = z0 + zmod * i * m;
        }
    } else {
        double m = dx / dz;
        double zrem = zmod * (iz + zo - zp);
        double xlimit = zrem * m;
        while (t < tExit) {
            double xrem = xmod * (ix + xo - xp);
            if (xrem < xlimit) {
                ix += xmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = i / dz + xrem / dx;
                    nx = -xmod;
                    nz = 0;
                    break;
                }
                iz += zmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = (i + zrem) / dz;
                    nx = 0;
                    nz = -zmod;
                    break;
                }
            } else {
                iz += zmod;
                if (Clouds.getCloud(ix, iz) == target) {
                    t = (i + zrem) / dz;
                    nx = 0;
                    nz = -zmod;
                    break;
                }
                if (xrem <= m) {
                    ix += xmod;
                    if (Clouds.getCloud(ix, iz) == target) {
                        t = i / dz + xrem / dx;
                        nx = -xmod;
                        nz = 0;
                        break;
                    }
                }
            }
            t = i / dz;
            i += 1;
            xp = x0 + xmod * i * m;
        }
    }
    int ny = 0;
    if (target == 1) {
        if (t > tExit) {
            return false;
        }
        ray.n.set(nx, ny, nz);
        onCloudEnter(ray, t + t_offset);
        return true;
    } else {
        if (t > tExit) {
            nx = 0;
            ny = (int) Math.signum(ray.d.y);
            nz = 0;
            t = tExit;
        } else {
            nx = -nx;
            nz = -nz;
        }
        ray.n.set(nx, ny, nz);
        onCloudExit(ray, t);
    }
    return true;
}

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

/**
 * Computes the present value sensitivity to the displaced diffusion (shift) parameters.
 * @param swaption The (physical delivery) swaption.
 * @param lmmData The LMM and multi-curves provider.
 * @return The sensitivity.//www. j a  v a  2 s. c o m
 */
public double[] presentValueDDSensitivity(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");
                }
            }
        }
        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[] 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.0 / 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 meanReversionImpact = (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr);
    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.0 / 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 double[] blkAdjoint = blackFunction.getPriceAdjoint(option, dataBlack);
    // Backward sweep
    final double pvBar = 1.0;
    final double impliedBlackVolBar = dfLMM[0] * blkAdjoint[2] * pvBar;
    final double normSigmaMBar = meanReversionImpact / (2.0 * impliedBlackVol) * impliedBlackVolBar;
    final double[] sigmaMBar = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        sigmaMBar[loopfact] = 2 * sigmaM[loopfact] * normSigmaMBar;
    }

    final double[][] muMBar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] = alphaM[loopcf + 1] * sigmaMBar[loopfact];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] += muMBar[loopcf + 1][loopfact];
        }
    }

    final double[] rateMRatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rateMRatioBar[loopcf] += gammaLMM[loopcf][loopfact] * muMBar[loopcf][loopfact];
        }
    }

    final double[] alphaMBar = new double[nbCF];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            alphaMBar[loopcf + 1] += muM[loopcf][loopfact] * sigmaMBar[loopfact];
        }
    }

    final double[] liborMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborMBar[loopcf] = ((liborM[loopcf] + 1 / deltaLMM[loopcf]) - (liborM[loopcf] + aLMM[loopcf]))
                / ((liborM[loopcf] + 1 / deltaLMM[loopcf]) * (liborM[loopcf] + 1 / deltaLMM[loopcf]))
                * rateMRatioBar[loopcf];
    }

    final double[] pMBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        pMBar[loopcf] += 1.0 / pM[loopcf + 1] / deltaLMM[loopcf] * liborMBar[loopcf];
        pMBar[loopcf + 1] += -pM[loopcf] / (pM[loopcf + 1] * pM[loopcf + 1]) / deltaLMM[loopcf]
                * liborMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pMBar[loopcf] += cfaMod[loopcf + 1] / bM * alphaMBar[loopcf];
    }

    double xBarBar = 0.0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        xBarBar += -p0[loopcf] * tau[loopcf] * pMBar[loopcf];
    }
    final double sumNumBar = 1.0 / sumDen * xBarBar;
    final double sumDenBar = -sumNum / (sumDen * sumDen) * xBarBar;
    final double[] tauBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] = -p0[loopcf] * xBar * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] += dP[loopcf] * sumDenBar;
    }
    final double[] tau2Bar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] = -p0[loopcf] / 2.0 * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] += -dP[loopcf] / 2.0 * sumNumBar;
    }
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        tau2Bar[loopcf + 1] += 1 / 2.0 / tau[loopcf + 1] * tauBar[loopcf + 1];
    }
    final double[][] mu0Bar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] = 2.0 * mu0[loopcf][loopfact] * meanReversionImpact * tau2Bar[loopcf + 1];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] += mu0Bar[loopcf + 1][loopfact];
        }
    }

    final double[] rate0RatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rate0RatioBar[loopcf] += gammaLMM[loopcf][loopfact] * mu0Bar[loopcf][loopfact];
        }
    }
    final double[] aLMMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        aLMMBar[loopcf] = 1.0 / (liborLMM[loopcf] + 1 / deltaLMM[loopcf]) * rate0RatioBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        aLMMBar[loopcf] += 1.0 / (liborM[loopcf] + 1 / deltaLMM[loopcf]) * rateMRatioBar[loopcf];
    }
    final double[] displacementBar = new double[volLMM.length];
    System.arraycopy(aLMMBar, 0, displacementBar, indStart, nbCF - 1);
    return displacementBar;
}

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

/**
* The theta, the sensitivity of the present value to a change in time to maturity, $\-frac{\partial V}{\partial T}$
*
* @param spot The spot value of the underlying
* @param strike The Strike/*  w w w  .j a  v  a 2  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, false for put
* @return theta
*/
@ExternalFunction
public static double theta(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");

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

    if (costOfCarry > LARGE) {
        return isCall ? Double.NEGATIVE_INFINITY : 0.;
    }
    if (-costOfCarry > LARGE) {
        final double res = isCall ? 0. : (discount > SMALL ? strike * discount * interestRate : 0.);
        return Double.isNaN(res) ? discount : res;
    }

    if (spot > LARGE * strike) {
        final double tmp = Math.exp((costOfCarry - interestRate) * timeToExpiry);
        final double res = isCall ? (tmp > SMALL ? -(costOfCarry - interestRate) * spot * tmp : 0.) : 0.;
        return Double.isNaN(res) ? tmp : res;
    }
    if (LARGE * spot < strike) {
        final double res = isCall ? 0. : (discount > SMALL ? strike * discount * interestRate : 0.);
        return Double.isNaN(res) ? discount : res;
    }
    if (spot > LARGE && strike > LARGE) {
        return Double.POSITIVE_INFINITY;
    }

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

    final int sign = isCall ? 1 : -1;
    double d1 = 0.;
    double d2 = 0.;
    if (Math.abs(spot - strike) < SMALL || sigmaRootT > LARGE) {
        final double coefD1 = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL)
                ? Math.signum(costOfCarry) + 0.5 * lognormalVol
                : (costOfCarry / lognormalVol + 0.5 * lognormalVol);
        final double tmpD1 = Math.abs(coefD1) < SMALL ? 0. : coefD1 * rootT;
        d1 = Double.isNaN(tmpD1) ? Math.signum(coefD1) : tmpD1;
        final double coefD2 = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL)
                ? Math.signum(costOfCarry) - 0.5 * lognormalVol
                : (costOfCarry / lognormalVol - 0.5 * lognormalVol);
        final double tmpD2 = Math.abs(coefD2) < SMALL ? 0. : coefD2 * rootT;
        d2 = Double.isNaN(tmpD2) ? Math.signum(coefD2) : tmpD2;
    } else {
        if (sigmaRootT < SMALL) {
            d1 = (Math.log(spot / strike) / rootT + costOfCarry * rootT) / lognormalVol;
            d2 = d1;
        } else {
            final double tmp = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL) ? rootT
                    : ((Math.abs(costOfCarry) < SMALL && rootT > LARGE) ? 1. / lognormalVol
                            : costOfCarry / lognormalVol * rootT);
            d1 = Math.log(spot / strike) / sigmaRootT + tmp + 0.5 * sigmaRootT;
            d2 = d1 - sigmaRootT;
        }
    }
    //    if (Double.isNaN(d1) || Double.isNaN(d2)) {
    //      throw new IllegalArgumentException("NaN found");
    //    }
    final double norm = NORMAL.getPDF(d1);
    final double rescaledSpot = Math.exp((costOfCarry - interestRate) * timeToExpiry) * spot;
    final double rescaledStrike = discount * strike;
    final double normForSpot = NORMAL.getCDF(sign * d1);
    final double normForStrike = NORMAL.getCDF(sign * d2);
    final double spotTerm = normForSpot < SMALL ? 0.
            : (Double.isNaN(rescaledSpot) ? -sign * Math.signum((costOfCarry - interestRate)) * rescaledSpot
                    : -sign * ((costOfCarry - interestRate) * rescaledSpot * normForSpot));
    final double strikeTerm = normForStrike < SMALL ? 0.
            : (Double.isNaN(rescaledSpot) ? sign * (-Math.signum(interestRate) * discount)
                    : sign * (-interestRate * rescaledStrike * normForStrike));

    double coef = rescaledSpot * lognormalVol / rootT;
    if (Double.isNaN(coef)) {
        coef = 1.; //ref value is returned
    }
    final double dlTerm = norm < SMALL ? 0. : -0.5 * norm * coef;

    final double res = dlTerm + spotTerm + strikeTerm;
    return Double.isNaN(res) ? 0. : res;
}

From source file:vc908.stickerfactory.ui.advancedrecyclerview.draggable.RecyclerViewDragDropManager.java

void handleScrollOnDragging() {
    final RecyclerView rv = mRecyclerView;
    final int height = rv.getHeight();

    if (height == 0) {
        return;/*  w  ww . ja v a  2  s .c  o  m*/
    }

    final float invHeight = (1.0f / height);
    final float y = mLastTouchY * invHeight;
    final float threshold = SCROLL_THRESHOLD;
    final float invThreshold = (1.0f / threshold);
    final float centerOffset = y - 0.5f;
    final float absCenterOffset = Math.abs(centerOffset);
    final float acceleration = Math.max(0.0f, threshold - (0.5f - absCenterOffset)) * invThreshold;
    final int mask = mScrollDirMask;

    int scrollAmount = (int) Math.signum(centerOffset)
            * (int) (SCROLL_AMOUNT_COEFF * mDisplayDensity * acceleration + 0.5f);
    int actualScrolledAmount = 0;

    final ItemDraggableRange range = mDraggableRange;

    final int firstVisibleChild = CustomRecyclerViewUtils.findFirstCompletelyVisibleItemPosition(mRecyclerView);
    final int lastVisibleChild = CustomRecyclerViewUtils.findLastCompletelyVisibleItemPosition(mRecyclerView);

    boolean reachedToTopHardLimit = false;
    boolean reachedToTopSoftLimit = false;
    boolean reachedToBottomHardLimit = false;
    boolean reachedToBottomSoftLimit = false;

    if (firstVisibleChild != RecyclerView.NO_POSITION) {
        if (firstVisibleChild <= range.getStart()) {
            reachedToTopSoftLimit = true;
        }
        if (firstVisibleChild <= (range.getStart() - 1)) {
            reachedToTopHardLimit = true;
        }
    }

    if (lastVisibleChild != RecyclerView.NO_POSITION) {
        if (lastVisibleChild >= range.getEnd()) {
            reachedToBottomSoftLimit = true;
        }
        if (lastVisibleChild >= (range.getEnd() + 1)) {
            reachedToBottomHardLimit = true;
        }
    }

    // apply mask
    if (scrollAmount > 0) {
        if ((mask & SCROLL_DIR_DOWN) == 0) {
            scrollAmount = 0;
        }
    } else if (scrollAmount < 0) {
        if ((mask & SCROLL_DIR_UP) == 0) {
            scrollAmount = 0;
        }
    }

    // scroll
    if ((!reachedToTopHardLimit && (scrollAmount < 0)) || (!reachedToBottomHardLimit && (scrollAmount > 0))) {
        safeEndAnimations(rv);
        actualScrolledAmount = scrollByYAndGetScrolledAmount(scrollAmount);

        if (scrollAmount < 0) {
            mDraggingItemDecorator.setIsScrolling(!reachedToTopSoftLimit);
        } else {
            mDraggingItemDecorator.setIsScrolling(!reachedToBottomSoftLimit);
        }

        mDraggingItemDecorator.refresh();
        if (mSwapTargetItemOperator != null) {
            mSwapTargetItemOperator.update(mDraggingItemDecorator.getDraggingItemTranslationY());
        }
    } else {
        mDraggingItemDecorator.setIsScrolling(false);
    }

    final boolean actualIsScrolling = (actualScrolledAmount != 0);

    if (mEdgeEffectDecorator != null) {
        final float edgeEffectStrength = 0.005f;

        final int draggingItemTop = mDraggingItemDecorator.getTranslatedItemPositionTop();
        final int draggingItemBottom = mDraggingItemDecorator.getTranslatedItemPositionBottom();
        final int draggingItemCenter = (draggingItemTop + draggingItemBottom) / 2;
        final int nearEdgePosition = ((draggingItemCenter < (height / 2)) ? draggingItemTop
                : draggingItemBottom);

        final float nearEdgeOffset = (nearEdgePosition * invHeight) - 0.5f;
        final float absNearEdgeOffset = Math.abs(nearEdgeOffset);
        float edgeEffectPullDistance = 0;

        if ((absNearEdgeOffset > 0.4f) && (scrollAmount != 0) && !actualIsScrolling) {
            if (nearEdgeOffset < 0) {
                // upward
                if (mDraggingItemDecorator.isReachedToTopLimit()) {
                    edgeEffectPullDistance = -mDisplayDensity * edgeEffectStrength;
                }
            } else {
                // downward
                if (mDraggingItemDecorator.isReachedToBottomLimit()) {
                    edgeEffectPullDistance = mDisplayDensity * edgeEffectStrength;
                }
            }
        }

        updateEdgeEffect(edgeEffectPullDistance);
    }

    ViewCompat.postOnAnimation(mRecyclerView, mCheckItemSwappingRunnable);
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this + value)}.
 *
 * @param value the value to be added to this {@link Rational}.
 * @return The addition result.//from  w w  w  . ja  va2 s .co m
 */
@Nonnull
public Rational add(float value) {
    if (isNaN() || Float.isNaN(value)) {
        return NaN;
    }

    if (value == 0f) {
        return this;
    }

    if (isInfinite()) {
        if (Float.isInfinite(value) && signum() != Math.signum(value)) {
            return NaN; // Infinity minus infinity
        }
        return this;
    }

    return add(valueOf(value));
}