List of usage examples for java.lang Math signum
public static float signum(float f)
From source file:netdecoder.NetDecoder.java
public int correlationChange(String gene, Map<String, Node> controlNetwork, Map<String, Node> diseaseNetwork) { int count = 1; if (controlNetwork.containsKey(gene) && diseaseNetwork.containsKey(gene)) { Node geneControl = controlNetwork.get(gene); Node geneDisease = diseaseNetwork.get(gene); List<Edge> edgesControl = geneControl.getEdges(); List<Edge> edgesDisease = geneDisease.getEdges(); List<Edge> aux = new ArrayList(edgesControl); aux.retainAll(edgesDisease);// w w w .java 2 s . c om for (Edge e : aux) { int iControl = edgesControl.indexOf(e); int iDisease = edgesDisease.indexOf(e); Double sigControl = Math.signum(edgesControl.get(iControl).getSignScore()); Double sigDisease = Math.signum(edgesDisease.get(iDisease).getSignScore()); if (!sigControl.equals(sigDisease)) { count++; //System.out.println(e + "\t" + edgesControl.get(iControl).getSignScore()); //System.out.println(e + "\t" + edgesDisease.get(iDisease).getSignScore()); } } } return count; }
From source file:org.apache.hadoop.mapred.CreditScheduler.java
/** * Dump scheduler state to the fairscheduler log. *//*from ww w . ja v a 2s. c o m*/ private synchronized void dump() { synchronized (eventLog) { eventLog.log("BEGIN_DUMP"); // List jobs in order of submit time ArrayList<JobInProgress> jobs = new ArrayList<JobInProgress>(infos.keySet()); Collections.sort(jobs, new Comparator<JobInProgress>() { public int compare(JobInProgress j1, JobInProgress j2) { return (int) Math.signum(j1.getStartTime() - j2.getStartTime()); } }); // Dump info for each job for (JobInProgress job : jobs) { JobProfile profile = job.getProfile(); JobInfo info = infos.get(job); Schedulable ms = info.mapSchedulable; Schedulable rs = info.reduceSchedulable; eventLog.log("JOB", profile.getJobID(), profile.name, profile.user, job.getPriority(), poolMgr.getPoolName(job), job.numMapTasks, ms.getRunningTasks(), ms.getDemand(), ms.getFairShare(), ms.getWeight(), job.numReduceTasks, rs.getRunningTasks(), rs.getDemand(), rs.getFairShare(), rs.getWeight()); } // List pools in alphabetical order List<Pool> pools = new ArrayList<Pool>(poolMgr.getPools()); Collections.sort(pools, new Comparator<Pool>() { public int compare(Pool p1, Pool p2) { if (p1.isDefaultPool()) return 1; else if (p2.isDefaultPool()) return -1; else return p1.getName().compareTo(p2.getName()); } }); for (Pool pool : pools) { int runningMaps = 0; int runningReduces = 0; for (JobInProgress job : pool.getJobs()) { JobInfo info = infos.get(job); if (info != null) { // TODO: Fix //runningMaps += info.runningMaps; //runningReduces += info.runningReduces; } } String name = pool.getName(); eventLog.log("POOL", name, poolMgr.getPoolWeight(name), pool.getJobs().size(), poolMgr.getAllocation(name, TaskType.MAP), runningMaps, poolMgr.getAllocation(name, TaskType.REDUCE), runningReduces); } // Dump info for each pool eventLog.log("END_DUMP"); } }
From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java
/** * The vanna of an option, i.e. second order derivative of the option value, once to the underlying spot and once to volatility.<p> * $\frac{\partial^2 FV}{\partial f \partial \sigma}$ * @param spot The spot value of the underlying * @param strike The Strike/* ww w . ja va2 s. com*/ * @param timeToExpiry The time-to-expiry * @param lognormalVol The log-normal volatility * @param interestRate The interest rate * @param costOfCarry The cost-of-carry rate * @return The spot vanna */ @ExternalFunction public static double vanna(final double spot, final double strike, final double timeToExpiry, final double lognormalVol, final double interestRate, final double costOfCarry) { 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"); final double rootT = Math.sqrt(timeToExpiry); double sigmaRootT = lognormalVol * rootT; if (Double.isNaN(sigmaRootT)) { sigmaRootT = 1.; //ref value is returned } double d1 = 0.; double d2 = 0.; if (Math.abs(spot - strike) < SMALL || (spot > LARGE && strike > LARGE) || sigmaRootT > LARGE) { final double coefD1 = Double.isNaN(Math.abs(costOfCarry) / lognormalVol) ? 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 = Double.isNaN(Math.abs(costOfCarry) / lognormalVol) ? 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) { final double scnd = (Math.abs(costOfCarry) > LARGE && rootT < SMALL) ? Math.signum(costOfCarry) : costOfCarry * rootT; final double tmp = (Math.log(spot / strike) / rootT + scnd) / lognormalVol; d1 = Double.isNaN(tmp) ? 0. : tmp; d2 = d1; } else { final double tmp = costOfCarry * rootT / lognormalVol; final double sig = (costOfCarry >= 0.) ? 1. : -1.; final double scnd = Double.isNaN(tmp) ? ((lognormalVol < LARGE && lognormalVol > SMALL) ? sig / lognormalVol : sig * rootT) : tmp; final double d1Tmp = Math.log(spot / strike) / sigmaRootT + scnd + 0.5 * sigmaRootT; final double d2Tmp = Math.log(spot / strike) / sigmaRootT + scnd - 0.5 * sigmaRootT; d1 = Double.isNaN(d1Tmp) ? 0. : d1Tmp; d2 = Double.isNaN(d2Tmp) ? 0. : d2Tmp; } } // if (Double.isNaN(d1) || Double.isNaN(d2)) { // throw new IllegalArgumentException("NaN found"); // } double coef = 0.; if ((interestRate > LARGE && costOfCarry > LARGE) || (-interestRate > LARGE && -costOfCarry > LARGE) || Math.abs(costOfCarry - interestRate) < SMALL) { coef = 1.; //ref value is returned } else { final double rate = costOfCarry - interestRate; if (rate > LARGE) { return costOfCarry > LARGE ? 0. : (d2 >= 0. ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); } if (-rate > LARGE) { return 0.; } coef = Math.exp(rate * timeToExpiry); } final double norm = NORMAL.getPDF(d1); double tmp = d2 * coef / lognormalVol; if (Double.isNaN(tmp)) { tmp = coef; } return norm < SMALL ? 0. : -norm * tmp; }
From source file:com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository.java
/** * Find the single volatility for a portfolio of European options such that the sum of Black prices of the options (with that volatility) * equals the (market) price of the portfolio - this is the implied volatility of the portfolio. A concrete example is a cap (floor) which * can be viewed as a portfolio of caplets (floorlets) * @param data basic description of each option * @param price The (market) price of the portfolio * @return The implied volatility of the portfolio *///from w w w .jav a 2 s.co m public static double impliedVolatility(final SimpleOptionData[] data, final double price) { Validate.notEmpty(data, "no option data given"); double intrinsicPrice = 0.0; for (final SimpleOptionData option : data) { intrinsicPrice += Math.max(0, (option.isCall() ? 1 : -1) * option.getDiscountFactor() * (option.getForward() - option.getStrike())); } Validate.isTrue(price >= intrinsicPrice, "option price (" + price + ") less than intrinsic value (" + intrinsicPrice + ")"); if (Double.doubleToLongBits(price) == Double.doubleToLongBits(intrinsicPrice)) { return 0.0; } double sigma = 0.3; final double maxChange = 0.5; double modelPrice = 0.0; double vega = 0.0; for (final SimpleOptionData option : data) { modelPrice += price(option, sigma); vega += vega(option, sigma); } if (vega == 0 || Double.isNaN(vega)) { return solveByBisection(data, price, sigma, 0.1); } double change = (modelPrice - price) / vega; double previousChange = 0.0; double sign = Math.signum(change); change = sign * Math.min(maxChange, Math.abs(change)); if (change > 0 && change > sigma) { change = sigma; } int count = 0; while (Math.abs(change) > VOL_TOL) { sigma -= change; modelPrice = 0.0; vega = 0.0; for (final SimpleOptionData option : data) { modelPrice += price(option, sigma); vega += vega(option, sigma); } if (vega == 0 || Double.isNaN(vega)) { return solveByBisection(data, price, sigma, 0.1); } change = (modelPrice - price) / vega; sign = Math.signum(change); change = sign * Math.min(maxChange, Math.abs(change)); if (change > 0 && change > sigma) { change = sigma; } // detect oscillation around the solution if (count > 5 && Math.abs(previousChange + change) < VOL_TOL) { change /= 2.0; } previousChange = change; if (count++ > MAX_ITERATIONS) { return solveByBisection(data, price, sigma, change); } } return sigma; }
From source file:mt.listeners.InteractiveRANSAC.java
public void updateRANSAC() { negcount = 0;//w ww .jav a2 s.c om negtimediff = 0; averageshrink = 0; catindex = 0; negsegments = new ArrayList<Pair<LinearFunction, ArrayList<PointFunctionMatch>>>(); ArrayList<Rateobject> allrates = new ArrayList<Rateobject>(); ArrayList<Averagerate> averagerates = new ArrayList<Averagerate>(); ++updateCount; dataset.removeAllSeries(); this.dataset.addSeries(Tracking.drawPoints(mts, calibrations)); @SuppressWarnings("unchecked") ArrayList<Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>>> segments = Tracking .findAllFunctions(points, function, maxError, minInliers, maxDist); if (segments == null || segments.size() == 0) { --updateCount; return; } // sort the segments according to time HORIZONTAL to each other and the // PointFunctionMatches internally sort(segments); final LinearFunction linear = new LinearFunction(); int linearcount = 1; i = 1; segment = 1; int count = 0; int rescount = 0; int catcount = 0; double timediff = 0; double restimediff = 0; double averagegrowth = 0; double growthrate = 0; double shrinkrate = 0; double minstartY = leastStart(segments); double minstartX = Double.MAX_VALUE; double minendX = Double.MAX_VALUE; double catfrequ = 0; double resfrequ = 0; double lifetime = 0; ArrayList<Double> previousendX = new ArrayList<Double>(); ResultsTable rt = new ResultsTable(); ResultsTable rtAll = new ResultsTable(); List<Pair<Float, Float>> starttimerates = new ArrayList<Pair<Float, Float>>(); List<Pair<Float, Float>> catstarttimerates = new ArrayList<Pair<Float, Float>>(); for (final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> result : segments) { if (LinearFunction.slopeFits(result.getB(), linear, minSlope, maxSlope)) { final Pair<Double, Double> minMax = Tracking.fromTo(result.getB()); double startX = minMax.getA(); double endX = minMax.getB(); if (startX < minstartX) { minstartX = startX; } if (endX < minendX) { minendX = endX; } Polynomial<?, Point> polynomial = (Polynomial) result.getA(); dataset.addSeries( Tracking.drawFunction(polynomial, minMax.getA(), minMax.getB(), 0.5, "Segment " + segment)); if (functionChoice > 0) { Tracking.setColor(chart, i, new Color(255, 0, 0)); Tracking.setDisplayType(chart, i, true, false); Tracking.setStroke(chart, i, 0.5f); chart.setTitle("Length plot for" + " " + this.inputfiles[row].getName()); } else { Tracking.setColor(chart, i, new Color(0, 128, 0)); Tracking.setDisplayType(chart, i, true, false); Tracking.setStroke(chart, i, 2f); chart.setTitle("Length plot for" + " " + this.inputfiles[row].getName()); } ++i; if (functionChoice > 0) { dataset.addSeries(Tracking.drawFunction(linear, minMax.getA(), minMax.getB(), 0.5, "Linear Segment " + segment)); Tracking.setColor(chart, i, new Color(0, 128, 0)); Tracking.setDisplayType(chart, i, true, false); Tracking.setStroke(chart, i, 2f); ++i; } double startY = polynomial.predict(startX); double linearrate = linear.getCoefficient(1); if (linearrate > 0 && startY - minstartY > restolerance && previousendX.size() > 0) { rescount++; restimediff += -previousendX.get(previousendX.size() - 1) + startX; } if (linearrate > 0) { count++; growthrate = linearrate; // Ignore last growth event for getting fcat if (points.get(points.size() - 1).getW()[0] - endX >= tptolerance) catcount++; timediff += endX - startX; lifetime = endX - startX; averagegrowth += linearrate; lifecount.add(new ValuePair<Integer, Double>(count, lifetime)); Rateobject velocity = new Rateobject(linearrate * calibrations[0] / calibrations[2], (int) (startX * calibrations[2]), (int) (endX * calibrations[2])); allrates.add(velocity); rt.incrementCounter(); rt.addValue("Start time", startX * calibrations[2]); rt.addValue("End time", endX * calibrations[2]); rt.addValue("Growth velocity", linearrate * calibrations[0] / calibrations[2]); Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX, (float) linearrate); starttimerates.add(startrate); } if (linearrate < 0) { negcount++; negtimediff += endX - startX; shrinkrate = linearrate; averageshrink += linearrate; rt.incrementCounter(); rt.addValue("Start time", startX * calibrations[2]); rt.addValue("End time", endX * calibrations[2]); rt.addValue("Growth velocity", linearrate * calibrations[0] / calibrations[2]); Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX, (float) linearrate); starttimerates.add(startrate); } if (linearrate > 0) { previousendX.add(endX); } dataset.addSeries(Tracking.drawPoints(Tracking.toPairList(result.getB()), calibrations, "Inliers " + segment)); Tracking.setColor(chart, i, new Color(255, 0, 0)); Tracking.setDisplayType(chart, i, false, true); Tracking.setSmallUpTriangleShape(chart, i); ++i; ++segment; } else { System.out.println("Removed segment because slope is wrong."); } } if (this.detectCatastrophe) { if (segments.size() < 2) { System.out.println("Only two points found"); } else { for (int catastrophy = 0; catastrophy < segments.size() - 1; ++catastrophy) { final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> start = segments.get(catastrophy); final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> end = segments .get(catastrophy + 1); double tStart = start.getB().get(start.getB().size() - 1).getP1().getL()[0]; double tEnd = end.getB().get(0).getP1().getL()[0]; final double lStart = start.getB().get(start.getB().size() - 1).getP1().getL()[1]; final double lEnd = end.getB().get(0).getP1().getL()[1]; final ArrayList<Point> catastropyPoints = new ArrayList<Point>(); for (final Point p : points) if (p.getL()[0] >= tStart && p.getL()[0] <= tEnd) catastropyPoints.add(p); if (catastropyPoints.size() > 2) { if (Math.abs(lStart - lEnd) >= this.minDistanceCatastrophe) { // maximally 1.1 timepoints between points on a line final Pair<LinearFunction, ArrayList<PointFunctionMatch>> fit = Tracking .findFunction(catastropyPoints, new LinearFunction(), 0.75, 3, 1.1); if (fit != null) { if (fit.getA().getM() < 0) { sort(fit); negsegments.add(fit); double minY = Math.min(fit.getB().get(0).getP1().getL()[1], fit.getB().get(fit.getB().size() - 1).getP1().getL()[1]); double maxY = Math.max(fit.getB().get(0).getP1().getL()[1], fit.getB().get(fit.getB().size() - 1).getP1().getL()[1]); final Pair<Double, Double> minMax = Tracking.fromTo(fit.getB()); double startX = minMax.getA(); double endX = minMax.getB(); double linearrate = fit.getA().getCoefficient(1); if (linearrate < 0) { dataset.addSeries(Tracking.drawFunction((Polynomial) fit.getA(), minMax.getA() - 1, minMax.getB() + 1, 0.1, minY - 2.5, maxY + 2.5, "CRansac " + catastrophy)); negcount++; negtimediff += endX - startX; shrinkrate = linearrate; averageshrink += linearrate; rt.incrementCounter(); rt.addValue("Start time", startX * calibrations[2]); rt.addValue("End time", endX * calibrations[2]); rt.addValue("Growth velocity", linearrate * calibrations[0] / calibrations[2]); Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX, (float) linearrate); starttimerates.add(startrate); Rateobject velocity = new Rateobject( linearrate * calibrations[0] / calibrations[2], (int) (startX * calibrations[2]), (int) (endX * calibrations[2])); allrates.add(velocity); Tracking.setColor(chart, i, new Color(0, 0, 255)); Tracking.setDisplayType(chart, i, true, false); Tracking.setStroke(chart, i, 2f); ++i; dataset.addSeries(Tracking.drawPoints(Tracking.toPairList(fit.getB()), calibrations, "C(inl) " + catastrophy)); Tracking.setColor(chart, i, new Color(0, 0, 255)); Tracking.setDisplayType(chart, i, false, true); Tracking.setShape(chart, i, ShapeUtils.createDownTriangle(4f)); ++i; } } } } else { System.out.println("Catastrophy height not sufficient " + Math.abs(lStart - lEnd) + " < " + this.minDistanceCatastrophe); } } } } } if (this.detectmanualCatastrophe) { catindex++; catstarttimerates = ManualCat(segments, allrates, shrinkrate, rt); } if (count > 0) averagegrowth /= count; if (catcount > 0) catfrequ = catcount / (timediff * calibrations[2]); if (rescount > 0) resfrequ = rescount / (restimediff * calibrations[2]); if (negcount > 0) averageshrink /= negcount; if (resfrequ < 0) resfrequ = 0; rt.show("Rates(real units) for" + " " + this.inputfile.getName()); averageshrink *= calibrations[0] / calibrations[2]; averagegrowth *= calibrations[0] / calibrations[2]; rtAll.incrementCounter(); rtAll.addValue("Average Growth", averagegrowth); rtAll.addValue("Growth events", count); rtAll.addValue("Average Shrink", averageshrink); rtAll.addValue("Shrink events", negcount); rtAll.addValue("Catastrophe Frequency", catfrequ); rtAll.addValue("Catastrophe events", catcount); rtAll.addValue("Rescue Frequency", resfrequ); rtAll.addValue("Rescue events", rescount); // rtAll.show("Average Rates and Frequencies (real units)"); starttimerates.addAll(catstarttimerates); sortTime(starttimerates); for (int index = 0; index < starttimerates.size() - 1; ++index) { int prevsign = (int) Math.signum(starttimerates.get(index).getB()); int nextsign = (int) Math.signum(starttimerates.get(index + 1).getB()); if (nextsign == prevsign) wrongfile = true; else wrongfile = false; wrongfileindex = new ValuePair<Boolean, Integer>(wrongfile, row); wrongfileindexlist.put(row, wrongfile); } table.getModel().setValueAt(new DecimalFormat("#.###").format(averagegrowth), row, 1); table.getModel().setValueAt(new DecimalFormat("#.###").format(averageshrink), row, 2); table.getModel().setValueAt(new DecimalFormat("#").format(count), row, 3); table.getModel().setValueAt(new DecimalFormat("#").format(negcount), row, 4); table.getModel().setValueAt(new DecimalFormat("#.###").format(catfrequ), row, 5); table.getModel().setValueAt(new DecimalFormat("#.###").format(resfrequ), row, 6); if (wrongfileindexlist.get(row) != null) { table.getModel().setValueAt(wrongfileindexlist.get(row).toString(), row, 7); } int size = 100; table.getColumnModel().getColumn(0).setPreferredWidth(size); table.getColumnModel().getColumn(1).setPreferredWidth(size); table.getColumnModel().getColumn(2).setPreferredWidth(size); table.getColumnModel().getColumn(3).setPreferredWidth(size); table.getColumnModel().getColumn(4).setPreferredWidth(size); table.getColumnModel().getColumn(5).setPreferredWidth(size); table.getColumnModel().getColumn(6).setPreferredWidth(size); table.getColumnModel().getColumn(7).setPreferredWidth(size); table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowA, int col) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, rowA, col); String status = (String) table.getModel().getValueAt(row, 7); if ("true".equals(status)) { setBackground(Color.GRAY); } else { setBackground(Color.GRAY); } return this; } }); table.validate(); scrollPane.validate(); Averagerate avrate = new Averagerate(averagegrowth, averageshrink, catfrequ, resfrequ, count, negcount, catcount, rescount, this.inputfile); averagerates.add(avrate); Compilepositiverates.put(row, allrates); Compileaverage.put(row, avrate); --updateCount; }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.java
/** * checks if the given string value contains string of form "0.1 to 0.5" and if it is, parses it and expands it into * according to amount of steps values and put them into pListFactors as floats *//* www. j a v a2 s.c om*/ private boolean isLoopFomatedFactor(final String pStrValue, final List<Float> pListFactors, final int pIntNumberIterations) throws CoreException { final String lStrRegex = "[ \\t]*[0-9][.,][0-9][ \\t]*[tT][oO][ \\t]*[0-9][.,][0-9][ \\t]*"; //$NON-NLS-1$ final String lStrToCheck = pStrValue.trim().toLowerCase(); if (Pattern.matches(lStrRegex, lStrToCheck)) { final int lIntIndexSep = lStrToCheck.indexOf("to"); //$NON-NLS-1$ final float lFloatStart = getFloatFromSimpleFloatString(lStrToCheck.substring(0, lIntIndexSep).trim()); final float lFloatEnd = getFloatFromSimpleFloatString(lStrToCheck.substring(lIntIndexSep + 2).trim()); if (lFloatStart < 0.0 || lFloatStart > 1.0 || lFloatEnd < 0.0 || lFloatEnd > 1.0) { final String msg = Messages.getString("org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.6");//$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, msg)); } final float lFloatInc = (float) ((lFloatEnd - lFloatStart) / 0.1); final int lIntPer = (int) (pIntNumberIterations / (Math.abs(lFloatInc) + 1)); int lIntInc = 0; final float lFloatSignum = Math.signum(lFloatInc); for (int i = 1; i <= pIntNumberIterations; ++i) { pListFactors.add((float) (lFloatStart + 0.1 * lIntInc * lFloatSignum)); if ((i) % lIntPer == 0 && pIntNumberIterations - i > Math.abs(lIntPer) && lIntInc < Math.abs(lFloatInc)) { lIntInc++; } } return true; } return false; }
From source file:com.android.launcher2.PagedView.java
@Override public boolean onTouchEvent(MotionEvent ev) { // Skip touch handling if there are no pages to swipe if (getChildCount() <= 0) return super.onTouchEvent(ev); acquireVelocityTrackerAndAddMovement(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /*/*w w w. j a va 2 s . c o m*/ * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = mLastMotionX = ev.getX(); mLastMotionXRemainder = 0; mTotalMotionX = 0; mActivePointerId = ev.getPointerId(0); if (mTouchState == TOUCH_STATE_SCROLLING) { pageBeginMoving(); } break; case MotionEvent.ACTION_MOVE: if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float deltaX = mLastMotionX + mLastMotionXRemainder - x; mTotalMotionX += Math.abs(deltaX); // Only scroll and update mLastMotionX if we have moved some discrete amount. We // keep the remainder because we are actually testing if we've moved from the last // scrolled position (which is discrete). if (Math.abs(deltaX) >= 1.0f) { mTouchX += deltaX; mSmoothingTime = System.nanoTime() / NANOTIME_DIV; if (!mDeferScrollUpdate) { scrollBy((int) deltaX, 0); if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); } else { invalidate(); } mLastMotionX = x; mLastMotionXRemainder = deltaX - (int) deltaX; } else { awakenScrollBars(); } } else { determineScrollingStart(ev); } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = ev.findPointerIndex(activePointerId); final float x = ev.getX(pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int velocityX = (int) velocityTracker.getXVelocity(activePointerId); final int deltaX = (int) (x - mDownMotionX); final int pageWidth = getScaledMeasuredWidth(getPageAt(mCurrentPage)); boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD; mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && Math.abs(velocityX) > mFlingThresholdVelocity; // In the case that the page is moved far to one direction and then is flung // in the opposite direction, we use a threshold to determine whether we should // just return to the starting page, or if we should skip one further. boolean returnToOriginalPage = false; if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && Math.signum(velocityX) != Math.signum(deltaX) && isFling) { returnToOriginalPage = true; } int finalPage; // We give flings precedence over large moves, which is why we short-circuit our // test for a large move if a fling has been registered. That is, a large // move to the left and fling to the right will register as a fling to the right. if (((isSignificantMove && deltaX > 0 && !isFling) || (isFling && velocityX > 0)) && mCurrentPage > 0) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; snapToPageWithVelocity(finalPage, velocityX); } else if (((isSignificantMove && deltaX < 0 && !isFling) || (isFling && velocityX < 0)) && mCurrentPage < getChildCount() - 1) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; snapToPageWithVelocity(finalPage, velocityX); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.max(0, mCurrentPage - 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { // at this point we have not moved beyond the touch slop // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so // we can just page int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); if (nextPage != mCurrentPage) { snapToPage(nextPage); } else { snapToDestination(); } } else { onUnhandledTap(ev); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; releaseVelocityTracker(); break; case MotionEvent.ACTION_CANCEL: if (mTouchState == TOUCH_STATE_SCROLLING) { snapToDestination(); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; releaseVelocityTracker(); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; }
From source file:geogebra.kernel.implicit.GeoImplicitPoly.java
private void startPath(int w, int h, double x, double y, GeoLocus locus) { double sx = x; double sy = y; double lx = Double.NaN; //no previous point double ly = Double.NaN; boolean first = true; double stepSize = START_STEP_SIZE * Math.max(scaleX, scaleY); double startX = x; double startY = y; ArrayList<MyPoint> firstDirPoints = new ArrayList<MyPoint>(); firstDirPoints.add(new MyPoint(x, y, true)); int s = 0;//from w ww .j a va 2 s. co m int lastW = w; int lastH = h; int startW = w; int startH = h; int stepCount = 0; boolean nearSing = false; double lastGradX = Double.POSITIVE_INFINITY; double lastGradY = Double.POSITIVE_INFINITY; while (true) { s++; boolean reachedSingularity = false; boolean reachedEnd = false; if (!Double.isNaN(lx) && !Double.isNaN(ly)) { if ((scaledNormSquared(startX - sx, startY - sy) < MAX_STEP_SIZE * MAX_STEP_SIZE) && (scaledNormSquared(startX - sx, startY - sy) < scaledNormSquared(startX - lx, startY - ly))) { /* loop found */ if (firstDirPoints != null) { MyPoint firstPoint = firstDirPoints.get(0); firstPoint.lineTo = false; locus.getPoints().addAll(firstDirPoints); } locus.insertPoint(x, y, true); return; } } while (sx < grid[w][h].x) { if (w > 0) w--; else { reachedEnd = true; break; } } while (sx > grid[w][h].x + grid[w][h].width) { if (w < grid.length - 1) w++; else { reachedEnd = true; break; } } while (sy < grid[w][h].y) { if (h > 0) h--; else { reachedEnd = true; break; } } while (sy > grid[w][h].y + grid[w][h].height) { if (h < grid[w].length - 1) h++; else { reachedEnd = true; break; } } if (reachedEnd) { //we reached the boundary boundaryIntersectCollection.add(new double[] { sx, sy }); } if (lastW != w || lastH != h) { int dw = (int) Math.signum(lastW - w); int dh = (int) Math.signum(lastH - h); for (int i = 0; i <= Math.abs(lastW - w); i++) { for (int j = 0; j <= Math.abs(lastH - h); j++) { remember[lastW - dw * i][lastH - dh * j] = false; } } } lastW = w; lastH = h; double gradX = 0; double gradY = 0; if (!reachedEnd) { gradX = evalDiffXPolyAt(sx, sy, true); gradY = evalDiffYPolyAt(sx, sy, true); /* * Dealing with singularities: tries to reach the singularity but stops there. * Assuming that the singularity is on or at least near the curve. (Since first * derivative is zero this can be assumed for 'nice' 2nd derivative) */ if (nearSing || (Math.abs(gradX) < NEAR_SING && Math.abs(gradY) < NEAR_SING)) { for (double[] pair : singularitiesCollection) { //check if this singularity is already known if ((scaledNormSquared(pair[0] - sx, pair[1] - sy) < SING_RADIUS * SING_RADIUS)) { sx = pair[0]; sy = pair[1]; reachedSingularity = true; reachedEnd = true; break; } } if (!reachedEnd) { if (gradX * gradX + gradY * gradY > lastGradX * lastGradX + lastGradY * lastGradY) { //going away from the singularity, stop here singularitiesCollection.add(new double[] { sx, sy }); reachedEnd = true; reachedSingularity = true; } else if (Math.abs(gradX) < MIN_GRAD && Math.abs(gradY) < MIN_GRAD) { //singularity singularitiesCollection.add(new double[] { sx, sy }); reachedEnd = true; reachedSingularity = true; } lastGradX = gradX; lastGradY = gradY; nearSing = true; } } } double a = 0, nX = 0, nY = 0; if (!reachedEnd) { a = 1 / (Math.abs(gradX) + Math.abs(gradY)); //trying to increase numerical stability gradX = a * gradX; gradY = a * gradY; a = Math.sqrt(gradX * gradX + gradY * gradY); gradX = gradX / a; //scale vector gradY = gradY / a; nX = -gradY; nY = gradX; if (!Double.isNaN(lx) && !Double.isNaN(ly)) { double c = (lx - sx) * nX + (ly - sy) * nY; if (c > 0) { nX = -nX; nY = -nY; } } else { if (!first) { //other dir now nX = -nX; nY -= nY; } } lx = sx; ly = sy; } while (!reachedEnd) { sx = lx + nX * stepSize; //go in "best" direction sy = ly + nY * stepSize; int e = epsSignum(evalPolyAt(sx, sy, true)); if (e == 0) { if (stepSize * 2 <= MAX_STEP_SIZE * Math.max(scaleX, scaleY)) stepSize *= 2; break; } else { gradX = evalDiffXPolyAt(sx, sy, true); gradY = evalDiffYPolyAt(sx, sy, true); if (Math.abs(gradX) < MIN_GRAD && Math.abs(gradY) < MIN_GRAD) { //singularity stepSize /= 2; if (stepSize > MIN_STEP_SIZE * Math.max(scaleX, scaleY)) continue; else { singularitiesCollection.add(new double[] { sx, sy }); reachedEnd = true; break; } } a = Math.sqrt(gradX * gradX + gradY * gradY); gradX *= stepSize / a; gradY *= stepSize / a; if (e > 0) { gradX = -gradX; gradY = -gradY; } int e1 = epsSignum(evalPolyAt(sx + gradX, sy + gradY, true)); if (e1 == 0) { sx = sx + gradX; sy = sy + gradY; break; } if (e1 != e) { a = bisec(sx, sy, sx + gradX, sy + gradY); sx += a * gradX; sy += a * gradY; break; } else { stepSize /= 2; if (stepSize > MIN_STEP_SIZE * Math.max(scaleX, scaleY)) continue; else { reachedEnd = true; break; } } } } if (!reachedEnd || reachedSingularity) { if (reachedSingularity || ((lx - sx) * (lx - sx) + (ly - sy) * (ly - sy) > minGap * minGap)) { if (firstDirPoints != null) { firstDirPoints.add(new MyPoint(sx, sy, true)); } else { locus.insertPoint(sx, sy, true); } stepCount++; } } if (reachedEnd) { if (!first) { return; //reached the end two times } lastGradX = Double.POSITIVE_INFINITY; lastGradY = Double.POSITIVE_INFINITY; /* we reached end for the first time and now save the points into the locus */ ArrayList<MyPoint> pointList = locus.getMyPointList(); if (firstDirPoints.size() > 0) { MyPoint lastPoint = firstDirPoints.get(firstDirPoints.size() - 1); lastPoint.lineTo = false; pointList.ensureCapacity(pointList.size() + firstDirPoints.size()); for (int i = firstDirPoints.size() - 1; i >= 0; i--) { pointList.add(firstDirPoints.get(i)); } } firstDirPoints = null; sx = startX; sy = startY; lx = Double.NaN; ly = Double.NaN; w = startW; h = startH; lastW = w; lastH = h; first = false;//start again with other direction reachedEnd = false; reachedSingularity = false; nearSing = false; } } }
From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java
/** * The dual vanna of an option, i.e. second order derivative of the option value, once to the strike and once to volatility. * @param spot The spot value of the underlying * @param strike The Strike//from w ww .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 * @return The spot dual vanna */ @ExternalFunction public static double dualVanna(final double spot, final double strike, final double timeToExpiry, final double lognormalVol, final double interestRate, final double costOfCarry) { 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"); final double rootT = Math.sqrt(timeToExpiry); double sigmaRootT = lognormalVol * rootT; if (Double.isNaN(sigmaRootT)) { sigmaRootT = 1.; //ref value is returned } double d1 = 0.; double d2 = 0.; if (Math.abs(spot - strike) < SMALL || (spot > LARGE && strike > LARGE) || sigmaRootT > LARGE) { final double coefD1 = Double.isNaN(Math.abs(costOfCarry) / lognormalVol) ? 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 = Double.isNaN(Math.abs(costOfCarry) / lognormalVol) ? 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) { final double scnd = (Math.abs(costOfCarry) > LARGE && rootT < SMALL) ? Math.signum(costOfCarry) : costOfCarry * rootT; final double tmp = (Math.log(spot / strike) / rootT + scnd) / lognormalVol; d1 = Double.isNaN(tmp) ? 0. : tmp; d2 = d1; } else { final double tmp = costOfCarry * rootT / lognormalVol; final double sig = (costOfCarry >= 0.) ? 1. : -1.; final double scnd = Double.isNaN(tmp) ? ((lognormalVol < LARGE && lognormalVol > SMALL) ? sig / lognormalVol : sig * rootT) : tmp; final double d1Tmp = Math.log(spot / strike) / sigmaRootT + scnd + 0.5 * sigmaRootT; final double d2Tmp = Math.log(spot / strike) / sigmaRootT + scnd - 0.5 * sigmaRootT; d1 = Double.isNaN(d1Tmp) ? 0. : d1Tmp; d2 = Double.isNaN(d2Tmp) ? 0. : d2Tmp; } } // if (Double.isNaN(d1) || Double.isNaN(d2)) { // throw new IllegalArgumentException("NaN found"); // } double coef = Math.exp(-interestRate * timeToExpiry); if (coef < SMALL) { return 0.; } if (Double.isNaN(coef)) { coef = 1.; //ref value is returned } final double norm = NORMAL.getPDF(d2); double tmp = d1 * coef / lognormalVol; if (Double.isNaN(tmp)) { tmp = coef; } return norm < SMALL ? 0. : norm * tmp; }
From source file:edu.utexas.cs.tactex.MarketManagerService.java
/** * @param timeslot// w w w. j a v a 2s . c o m * @param neededMwh * @param remainingTries * @param lowerLimit * @param upperlimit * @param currentTimeslotIndex * @return */ private Double origLimitComputation(int timeslot, double neededMwh, double upperlimit, int currentTimeslotIndex) { log.debug("Compute limit for " + neededMwh + ", timeslot " + timeslot); // start with default limits double maxPrice; double minPrice; if (neededMwh > 0.0) { // buying maxPrice = BUY_LIMIT_PRICE_MAX; minPrice = BUY_LIMIT_PRICE_MIN; } else { // selling maxPrice = SELL_LIMIT_PRICE_MAX; minPrice = SELL_LIMIT_PRICE_MIN; } // check for escalation Order lastTry = lastOrder.get(timeslot); if (lastTry != null) log.debug("lastTry: " + lastTry.getMWh() + " at " + lastTry.getLimitPrice()); if (lastTry != null && Math.signum(neededMwh) == Math.signum(lastTry.getMWh())) { Double tmp = lastTry.getLimitPrice(); if (tmp != null) { // shouldn't happen.. but happened due to sync issues maxPrice = tmp; log.debug("old limit price: " + maxPrice); } } // set price between maxPrice and minPrice, according to number of // remaining chances we have to get what we need. int remainingTries = (timeslot - currentTimeslotIndex - Competition.currentCompetition().getDeactivateTimeslotsAhead()); log.debug("remainingTries: " + remainingTries); if (remainingTries > 0) { double range = (minPrice - maxPrice) * 2.0 / (double) remainingTries; log.debug("maxPrice=" + maxPrice + ", range=" + range); double computedPrice = maxPrice + randomGen.nextDouble() * range; return Math.min(Math.max(minPrice, computedPrice), upperlimit); } else return null; // market order }