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:gedi.util.math.stat.distributions.GeneralizedExtremeValueDistribution.java

public static GeneralizedExtremeValueDistribution fitDataByMoments(double[] data, int start, int end) {
    int n = end - start;
    if (n < 2)
        throw new RuntimeException("Too few data!");
    Arrays.sort(data, start, end);

    // compute moments
    final double[] b = new double[3];
    for (int j = 1; j <= n; j++) {
        int index = j - 1 - start;
        b[0] += data[index];/*  w  ww.ja v  a  2  s.co  m*/
        b[1] += data[index] * ((j - 1.0) / (n - 1.0));
        b[2] += data[index] * ((j - 1.0) / (n - 1.0)) * ((j - 2.0) / (n - 2.0));
    }
    b[0] /= n;
    b[1] /= n;
    b[2] /= n;

    // solve parameters
    UnivariateFunction f = new UnivariateFunction() {
        public double value(double k) {
            return (3 * b[2] - b[0]) / (2 * b[1] - b[0]) - (1 - Math.pow(3, -k)) / (1 - Math.pow(2, -k));
        }
    };
    double k;

    if (Math.signum(f.value(-0.5)) != Math.signum(f.value(0.5)))
        k = UnivariateSolverUtils.solve(f, -0.5, 0.5);
    else {
        double c = (2 * b[1] - b[0]) / (3 * b[2] - b[0]) - Math.log(2) / Math.log(3);
        k = 7.859 * c + 2.9554 * c * c;
    }

    double g = Gamma.gamma(1 + k);
    double alpha = ((2 * b[1] - b[0]) * k) / (g * (1 - Math.pow(2, -k)));
    double xi = b[0] + alpha * (g - 1) / k;

    double location = xi;
    double scale = alpha;
    double shape = -k;

    return new GeneralizedExtremeValueDistribution(location, scale, shape);
}

From source file:com.precioustech.fxtrading.tradingbot.strategies.FadeTheMoveStrategy.java

public void analysePrices() {
    for (Map.Entry<TradeableInstrument<T>, Cache<DateTime, MarketDataPayLoad<T>>> entry : instrumentRecentPricesCache
            .entrySet()) {/*from   ww w. j ava2 s  .co  m*/
        SortedMap<DateTime, MarketDataPayLoad<T>> sortedByDate = ImmutableSortedMap
                .copyOf(entry.getValue().asMap());
        if (sortedByDate.isEmpty()) {
            continue;
        }
        Double pipJump = calculatePipJump(sortedByDate.values(), entry.getKey());
        Double absPipJump = Math.abs(pipJump);
        if (absPipJump >= this.pipJumpCutOffCalculator.calculatePipJumpCutOff(entry.getKey())) {
            MarketDataPayLoad<T> lastPayLoad = sortedByDate.get(sortedByDate.lastKey());
            Double pip = this.instrumentService.getPipForInstrument(entry.getKey());
            double takeProfitPrice;
            double limitPrice;
            TradingSignal signal = null;
            if (Math.signum(pipJump) > 0) {// Short
                signal = TradingSignal.SHORT;
                limitPrice = lastPayLoad.getBidPrice() + tradingConfig.getFadeTheMoveDistanceToTrade() * pip;
                takeProfitPrice = limitPrice - tradingConfig.getFadeTheMovePipsDesired() * pip;
            } else {
                signal = TradingSignal.LONG;
                limitPrice = lastPayLoad.getAskPrice() - tradingConfig.getFadeTheMoveDistanceToTrade() * pip;
                takeProfitPrice = limitPrice + tradingConfig.getFadeTheMovePipsDesired() * pip;
            }
            this.orderQueue.offer(new TradingDecision<T>(entry.getKey(), signal, takeProfitPrice, 0.0,
                    limitPrice, TradingDecision.SRCDECISION.FADE_THE_MOVE));
            entry.getValue().asMap().clear();/*
                                              * clear the prices so that we do not keep
                                              * working on old decision
                                              */
        }
    }
}

From source file:com.comphenix.xp.SampleRange.java

private int sampleIntReduced(Random rnd) {
    double value = sampleDouble(rnd);

    // Probability of adding the fraction
    double fraction = value - Math.floor(value);
    double toAdd = rnd.nextDouble() < fraction ? Math.signum(value) : 0;

    return (int) value + (int) toAdd;
}

From source file:org.kuali.rice.krad.demo.uif.lookup.LookupableTravelImpl.java

/**
 * Validates that any wildcards contained within the search value are valid wildcards and allowed for the
 * property type for which the field is searching.
 *
 * @param inputField attribute field instance for the field that is being searched
 * @param searchPropertyValue value given for field to search for
 *///from   w  w  w.  j a  v  a  2  s.  c  o  m
protected void validateSearchParameterPositiveValues(InputField inputField, String searchPropertyValue) {
    if (StringUtils.isBlank(searchPropertyValue)) {
        return;
    }

    NumberFormat format = NumberFormat.getInstance();
    Number number = null;
    try {
        number = format.parse(searchPropertyValue);
    } catch (ParseException e) {
        return;
    }

    if (Math.signum(number.doubleValue()) < 0) {
        String attributeLabel = inputField.getLabel();
        GlobalVariables.getMessageMap().putError(inputField.getPropertyName(),
                RiceKeyConstants.ERROR_NEGATIVES_NOT_ALLOWED_ON_FIELD, attributeLabel);
    }
}

From source file:pl.dpbz.poid.zadanie4.filter.SOIWahWah.java

@Override
public void setSignalWindows(Integer[] samples) {
    super.setSignalWindows(samples); //To change body of generated methods, choose Tools | Templates.
    oscilationFunction = new double[samples.length];
    oscilationFunction[0] = leftSideFreq;
    for (int i = 1; i < oscilationFunction.length; i++) {
        oscilationFunction[i] = oscilationFunction[i - 1] + ((rightSideFreq - leftSideFreq))
                * Math.signum(Math.sin(2.0 * Math.PI * i * frequency / SAMPLING_FREQUENCY));
    }//from   w  w w . j  a v  a2  s. c o m
}

From source file:com.example.android.supportv7.widget.touch.SwipeToDismissActivity.java

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX,
        float dY, int actionState, boolean isCurrentlyActive) {
    if (!mCustomSwipeEnabled) {
        return false;
    }/*from   w ww .  j  av  a  2 s.co  m*/
    ItemTouchViewHolder touchVH = (ItemTouchViewHolder) viewHolder;
    final float dir = Math.signum(dX);
    if (dir == 0) {
        touchVH.overlay.setTranslationX(-touchVH.overlay.getWidth());
    } else {
        final float overlayOffset = dX - dir * viewHolder.itemView.getWidth();
        touchVH.overlay.setTranslationX(overlayOffset);
    }
    float alpha = (float) (.2 + .8 * Math.abs(dX) / viewHolder.itemView.getWidth());
    touchVH.overlay.setAlpha(alpha);
    return true;
}

From source file:ch.algotrader.option.SABR.java

private static double getSmallestRoot(double cubic, double quadratic, double linear, double constant) {

    double a = quadratic / cubic;
    double b = linear / cubic;
    double C = constant / cubic;
    double Q = (Math.pow(a, 2) - 3 * b) / 9.0;
    double r = (2 * Math.pow(a, 3) - 9 * a * b + 27 * C) / 54.0;

    double root = 0;

    if (Math.pow(r, 2) - Math.pow(Q, 3) >= 0) {

        double capA = -Math.signum(r)
                * Math.pow(Math.abs(r) + Math.sqrt(Math.pow(r, 2) - Math.pow(Q, 3)), 1.0 / 3.0);
        double capB = 0;
        if (capA != 0) {
            capB = Q / capA;// w  w  w .j  av  a2 s  .c  o  m
        }
        root = capA + capB - a / 3.0;

    } else {

        double theta = Math.acos(r / Math.pow(Q, 1.5));
        double root1 = -2 * Math.sqrt(Q) * Math.cos(theta / 3.0) - a / 3.0;
        double root2 = -2 * Math.sqrt(Q) * Math.cos(theta / 3.0 + 2.0943951023932) - a / 3.0;
        double root3 = -2 * Math.sqrt(Q) * Math.cos(theta / 3.0 - 2.0943951023932) - a / 3.0;

        // find the smallest positive one
        if (root1 > 0) {
            root = root1;
        } else if (root2 > 0) {
            root = root2;
        } else if (root3 > 0) {
            root = root3;
        }

        if (root2 > 0 && root2 < root) {
            root = root2;
        }
        if (root3 > 0 && root3 < root) {
            root = root3;
        }
    }

    return root;
}

From source file:org.jcurl.core.impl.BisectionCollissionDetector.java

public double compute(final double t0, final double tstop, final R1RNFunction fa, final R1RNFunction fb,
        final double distSq) {
    if (false) {//  www .  j  a  va 2s  .  co m
        // TUNE test only rocks really in motion
        final double[] tmp = { 0, 0, 0 };
        fa.at(t0, 1, tmp);
        final boolean fa_still = tmp[0] * tmp[0] + tmp[1] * tmp[1] < 1e-9;
        fb.at(t0, 1, tmp);
        if (fa_still && tmp[0] * tmp[0] + tmp[1] * tmp[1] < 1e-9)
            return Double.NaN;
    }
    if (false) {
        final R1R1Function dist = new Distance2DSq(fa, fb, 0);
        final R1R1Function f = new R1R1Function() {
            private static final long serialVersionUID = 7051701140539614770L;

            @Override
            public double at(final double x, final int c) {
                if (c == 0)
                    return dist.at(x, 0) * -Math.signum(dist.at(x, 1));
                if (c == 1)
                    return Math.abs(dist.at(x, 1));
                throw new IllegalArgumentException();
            }
        };
        final double r = BisectionSolver.findRoot(f, CollissionDetector.RR2, t0, tstop, 1e-9);
        if (log.isDebugEnabled())
            log.debug(dist.at(r) - CollissionDetector.RR2);
        if (Double.isNaN(r) || Math.abs(dist.at(r) - CollissionDetector.RR2) > 1e-6)
            return Double.NaN;
        return r;
    } else {
        final Distance2DSqFlipped f = new Distance2DSqFlipped(fa, fb, 0);
        final double r = BisectionSolver.findRoot(f, CollissionDetector.RR2, t0, tstop, 1e-9);
        if (log.isDebugEnabled())
            log.debug(f.unflipped(r) - CollissionDetector.RR2);
        if (Double.isNaN(r) || Math.abs(f.unflipped(r) - CollissionDetector.RR2) > 1e-6)
            return Double.NaN;
        return r;
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.voyager.policies.AggressivePolicy.java

@Override
public VoyagerAction getAction() {
    // Locate a large friendly force
    final ArrayList<Planet> friendly = Voyager.playerPlanets(s_, player_);
    Collections.sort(friendly, new Comparator<Planet>() {
        @Override/*from  w ww.j  a  v a2s.  com*/
        public int compare(final Planet a, final Planet b) {
            return b.population(Unit.Soldier) - a.population(Unit.Soldier);
        }
    });

    final Planet primary = (friendly.isEmpty() ? null : friendly.get(0));
    final Planet secondary = (friendly.size() <= 1 ? null : friendly.get(1));
    final int primary_force = (primary != null ? primary.population(Unit.Soldier) - garrison_ : 0);
    final int secondary_force = (secondary != null ? secondary.population(Unit.Soldier) - garrison_ : 0);
    final int force = primary_force + secondary_force;

    if (primary != null) {
        // Sort enemy planets by defense strength per worker
        final ArrayList<Planet> enemy = Voyager.playerPlanets(s_, player_.enemy());
        Collections.sort(enemy, new Comparator<Planet>() {
            @Override
            public int compare(final Planet a, final Planet b) {
                final int[] apop = Voyager.effectivePopulation(s_, a, player_.enemy());
                final int[] bpop = Voyager.effectivePopulation(s_, b, player_.enemy());
                final double aratio = apop[Unit.Worker.ordinal()] > 0
                        ? Voyager.defense_strength(apop) / apop[Unit.Worker.ordinal()]
                        : Double.MAX_VALUE;
                final double bratio = bpop[Unit.Worker.ordinal()] > 0
                        ? Voyager.defense_strength(bpop) / bpop[Unit.Worker.ordinal()]
                        : Double.MAX_VALUE;
                return (int) Math.signum(aratio - bratio);
            }
        });
        // Find the enemy Planet with the best worker ratio that we have
        // enough forces to take over.
        for (final Planet p : enemy) {
            final int[] pop = Voyager.effectivePopulation(s_, p, player_.enemy());
            final int d = Voyager.defense_strength(pop);
            final int a = Voyager.attack_strength(new int[] { 0, primary_force });
            if (a > d) {
                return new LaunchAction(primary, p, new int[] { 0, primary_force });
            }
        }

        // If there isn't a promising attack available, shift some soldiers
        for (final Planet p : friendly) {
            if (!p.equals(primary) && !p.equals(secondary)) {
                final int soldiers = p.population(Unit.Soldier) - garrison_;
                if (soldiers > 0) {
                    return new LaunchAction(p, primary, new int[] { 0, soldiers });
                }
            }
        }
    }

    // If there are no soldiers to shift, optimize production
    for (final Planet p : friendly) {
        if (p.nextProduced() == Unit.Worker && p.population(Unit.Worker) >= p.capacity) {
            return new SetProductionAction(p, Unit.Soldier);
        }
    }

    return new NothingAction();
}

From source file:us.fatehi.pointlocation6709.format.PointLocationFormatter.java

private static String formatAltitudeWithSign(final double value) {
    if (Math.abs(value) > 1E-6) {
        return (Math.signum(value) < 0 ? "-" : "+") + getNumberFormat(1).format(Math.abs(value));
    } else {/*from   w  w  w  . jav a 2  s  . c o  m*/
        return "";
    }
}