List of usage examples for java.lang Double compare
public static int compare(double d1, double d2)
From source file:org.apache.mahout.freqtermsets.AggregatorReducer.java
@Override protected void reduce(Text key, Iterable<TopKStringPatterns> values, Context context) throws IOException, InterruptedException { // YA get data to do more than freq merge int myMaxHeapSize = maxHeapSize; Configuration conf = context.getConfiguration(); FileSystem fs = FileSystem.get(conf); //TODO: do I need?getLocal(conf); String cachePath = FilenameUtils.concat(FileUtils.getTempDirectory().toURI().toString(), Thread.currentThread().getName() + "_" + key.hashCode() + "_patterns"); org.apache.hadoop.io.ArrayFile.Writer cacheWr = new ArrayFile.Writer(conf, fs, cachePath, TopKStringPatterns.class); final String keyStr = key.toString(); final OpenObjectLongHashMap<String> jointFreq = new OpenObjectLongHashMap<String>(); TopKStringPatterns metaPatterns = new TopKStringPatterns(); for (TopKStringPatterns value : values) { List<Pair<List<String>, Long>> vPatterns = value.getPatterns(); for (int p = vPatterns.size() - 1; p >= 0; --p) { Pair<List<String>, Long> pattern = vPatterns.get(p); if (pattern == null) { continue; // just like their merge }/*from w w w.java 2 s. c o m*/ for (String other : pattern.getFirst()) { if (other.charAt(0) == METADATA_PREFIX) { // Keep metadata out of merge vPatterns.remove(p); // Make sure it has space to be merged ++myMaxHeapSize; // Store the metadata temporarily.. we will add it in the end // where it can't be pruned out metaPatterns.getPatterns().add(pattern); // done processing metadata itemset break; } if (keyStr.equals(other)) { continue; } long freq = jointFreq.get(other); if (pattern.getSecond() > freq) { freq = pattern.getSecond(); } jointFreq.put(other, freq); } } cacheWr.append(value); } cacheWr.close(); org.apache.hadoop.io.ArrayFile.Reader cacheRd = new ArrayFile.Reader(fs, cachePath, conf); // END YA get data TopKStringPatterns patterns = new TopKStringPatterns(); TopKStringPatterns value = new TopKStringPatterns(); while (cacheRd.next(value) != null) { context.setStatus("Aggregator Reducer: Selecting TopK patterns for: " + key); // YA Mutual info merge.. TODO: more metrics passed as class name of comparator if (sortByMutualInfo) { patterns = patterns.merge(value, myMaxHeapSize, new Comparator<Pair<List<String>, Long>>() { private double calcNormalizedMutualInfo(String[] bagOfTokens) { double numer = 0; double denim = 0; double ft1 = fMap.get(keyStr); for (int t2 = 0; t2 < bagOfTokens.length; ++t2) { if (bagOfTokens[t2].equals(keyStr)) { continue; } double ft2 = fMap.get(bagOfTokens[t2]); double jf = jointFreq.get(bagOfTokens[t2]); // This check shouldn't be even plausible.. save time: // if(jf != 0){ double jp = jf / totalNterms; numer += jp * (Math.log(jf / (ft1 * ft2)) + lnTotalNTerms); denim += jp * Math.log(jp); } double result = numer; if (denim != 0) { result /= -denim; } return result; } @Override public int compare(Pair<List<String>, Long> o1, Pair<List<String>, Long> o2) { String[] bagOfTokens = o1.getFirst().toArray(new String[0]); double mi1 = calcNormalizedMutualInfo(bagOfTokens); bagOfTokens = o2.getFirst().toArray(new String[0]); double mi2 = calcNormalizedMutualInfo(bagOfTokens); int result = Double.compare(mi1, mi2); if (result == 0) { result = Double.compare(o1.getFirst().size(), o2.getFirst().size()); if (result == 0) { result = o1.getSecond().compareTo(o2.getSecond()); } } return result; } }); // END YA Mutual info merge } else { patterns = patterns.mergeFreq(value, myMaxHeapSize); } } // YA get data cacheRd.close(); fs.delete(new Path(cachePath), true); patterns = patterns.merge(metaPatterns, myMaxHeapSize, new Comparator<Pair<List<String>, Long>>() { @Override public int compare(Pair<List<String>, Long> o1, Pair<List<String>, Long> o2) { // Force the metadata to be accepted return -1; } }); // END YA get data context.write(key, patterns); }
From source file:eionet.cr.util.sesame.ResultCompareUtil.java
/** * * @param bs1/*from w ww.j av a 2s .c o m*/ * @param bs2 * @param bNodeMapping * @return */ private static boolean bindingSetsMatch(BindingSet bs1, BindingSet bs2, Map<BNode, BNode> bNodeMapping) { if (bs1.size() != bs2.size()) { return false; } for (Binding binding1 : bs1) { Value value1 = binding1.getValue(); Value value2 = bs2.getValue(binding1.getName()); if (value1 instanceof BNode && value2 instanceof BNode) { BNode mappedBNode = bNodeMapping.get(value1); if (mappedBNode != null) { // bNode 'value1' was already mapped to some other bNode if (!value2.equals(mappedBNode)) { // 'value1' and 'value2' do not match return false; } } else { // 'value1' was not yet mapped, we need to check if 'value2' is a // possible mapping candidate if (bNodeMapping.containsValue(value2)) { // 'value2' is already mapped to some other value. return false; } } } else { if (!StringUtils.equals(value1.stringValue(), value2.stringValue())) { return false; } // values are not (both) bNodes if (value1 instanceof Literal && value2 instanceof Literal) { // do literal value-based comparison for supported datatypes Literal leftLit = (Literal) value1; Literal rightLit = (Literal) value2; URI dt1 = leftLit.getDatatype(); URI dt2 = rightLit.getDatatype(); if (dt1 != null && dt2 != null && dt1.equals(dt2) && XMLDatatypeUtil.isValidValue(leftLit.getLabel(), dt1) && XMLDatatypeUtil.isValidValue(rightLit.getLabel(), dt2)) { Integer compareResult = null; if (dt1.equals(XMLSchema.DOUBLE)) { compareResult = Double.compare(leftLit.doubleValue(), rightLit.doubleValue()); } else if (dt1.equals(XMLSchema.FLOAT)) { compareResult = Float.compare(leftLit.floatValue(), rightLit.floatValue()); } else if (dt1.equals(XMLSchema.DECIMAL)) { compareResult = leftLit.decimalValue().compareTo(rightLit.decimalValue()); } else if (XMLDatatypeUtil.isIntegerDatatype(dt1)) { compareResult = leftLit.integerValue().compareTo(rightLit.integerValue()); } else if (dt1.equals(XMLSchema.BOOLEAN)) { Boolean leftBool = Boolean.valueOf(leftLit.booleanValue()); Boolean rightBool = Boolean.valueOf(rightLit.booleanValue()); compareResult = leftBool.compareTo(rightBool); } else if (XMLDatatypeUtil.isCalendarDatatype(dt1)) { XMLGregorianCalendar left = leftLit.calendarValue(); XMLGregorianCalendar right = rightLit.calendarValue(); compareResult = left.compare(right); } if (compareResult != null) { if (compareResult.intValue() != 0) { return false; } } else if (!value1.equals(value2)) { return false; } } else if (!value1.equals(value2)) { return false; } } else if (!value1.equals(value2)) { return false; } } } return true; }
From source file:ca.mudar.parkcatcher.ui.activities.MainActivity.java
@SuppressWarnings("deprecation") @Override/*from w w w . ja v a2 s. c o m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!Const.IS_DEBUG) { Crittercism.init(getApplicationContext(), Const.CRITTERCISM_APP_ID); } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); activityHelper = ActivityHelper.createInstance(this); parkingApp = (ParkingApp) getApplicationContext(); parkingApp.updateUiLanguage(); /** * Display the GPLv3 licence */ if (!EulaHelper.hasAcceptedEula(this)) { if (ConnectionHelper.hasConnection(this)) { EulaHelper.showEula(false, this); } else { setContentView(R.layout.activity_no_connection); setSupportProgressBarIndeterminateVisibility(Boolean.FALSE); return; } } hasLoadedData = parkingApp.hasLoadedData(); if (!hasLoadedData) { hasLoadedData = true; // The service runs in the background with no listener Intent intent = new Intent(Intent.ACTION_SYNC, null, getApplicationContext(), SyncService.class); intent.putExtra(Const.INTENT_EXTRA_SERVICE_LOCAL, false); intent.putExtra(Const.INTENT_EXTRA_SERVICE_REMOTE, true); startService(intent); } isPlayservicesOutdated = (GooglePlayServicesUtil .isGooglePlayServicesAvailable(getApplicationContext()) != ConnectionResult.SUCCESS); if (isPlayservicesOutdated) { disableLocationUpdates(); isCenterOnMyLocation = false; setContentView(R.layout.activity_playservices_update); setSupportProgressBarIndeterminateVisibility(Boolean.FALSE); return; } else { setContentView(R.layout.activity_main); setSupportProgressBarIndeterminateVisibility(Boolean.FALSE); } // Set the layout containing the two fragments // Get the fragments FragmentManager fm = getSupportFragmentManager(); mMapFragment = (MapFragment) fm.findFragmentByTag(Const.TAG_FRAGMENT_MAP); mFavoritesFragment = (FavoritesFragment) fm.findFragmentByTag(Const.TAG_FRAGMENT_FAVORITES); // Create the actionbar tabs final ActionBar ab = getSupportActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ab.addTab(ab.newTab().setText(R.string.tab_map).setTabListener(this).setTag(Const.TAG_TABS_MAP)); ab.addTab( ab.newTab().setText(R.string.tab_favorites).setTabListener(this).setTag(Const.TAG_TABS_FAVORITES)); initLocation = null; double latitude = getIntent().getDoubleExtra(Const.INTENT_EXTRA_GEO_LAT, Double.MIN_VALUE); double longitude = getIntent().getDoubleExtra(Const.INTENT_EXTRA_GEO_LNG, Double.MIN_VALUE); if (Double.compare(latitude, Double.MIN_VALUE) != 0 && Double.compare(latitude, Double.MIN_VALUE) != 0) { initLocation = new Location(Const.LOCATION_PROVIDER_INTENT); initLocation.setLatitude(latitude); initLocation.setLongitude(longitude); isCenterOnMyLocation = false; } else { isCenterOnMyLocation = true; // Initialize the displayed values. This is not done when // MainActivity is called from Details activity, to keep the same // Calendar. parkingApp.resetParkingCalendar(); } updateParkingTimeTitle(); updateParkingDateButton(); updateParkingTimeButton(); updateParkingDurationButton(); mFavoritesFragment.refreshList(); mDrawer = (SlidingDrawer) findViewById(R.id.drawer_time); mDrawer.animateOpen(); }
From source file:org.diorite.utils.math.DioriteRandomUtils.java
public static double getRandomDouble(final Random random, final double min, final double max) throws IllegalArgumentException { if (Double.compare(min, max) == 0) { return max; }/*from ww w .j av a2 s.c o m*/ Validate.isTrue(max > min, "Max can't be smaller than min!"); return (random.nextDouble() * (max - min)) + min; }
From source file:com.opengamma.financial.analytics.volatility.surface.BloombergEquityIndexFutureOptionVolatilitySurfaceInstrumentProvider.java
@Override public boolean equals(final Object obj) { if (this == obj) { return true; }//w ww.j a v a 2 s . c o m if (!(obj instanceof BloombergEquityIndexFutureOptionVolatilitySurfaceInstrumentProvider)) { return false; } final BloombergEquityIndexFutureOptionVolatilitySurfaceInstrumentProvider other = (BloombergEquityIndexFutureOptionVolatilitySurfaceInstrumentProvider) obj; if (Double.compare(_useCallAboveStrike, other._useCallAboveStrike) != 0) { return false; } if (!ObjectUtils.equals(_futureOptionPrefix, other._futureOptionPrefix)) { return false; } if (!ObjectUtils.equals(_exchangeIdName, other._exchangeIdName)) { return false; } if (!ObjectUtils.equals(_tickerSchemeName, other._tickerSchemeName)) { return false; } if (!ObjectUtils.equals(_dataFieldName, other._dataFieldName)) { return false; } if (!ObjectUtils.equals(_postfix, other._postfix)) { return false; } return true; }
From source file:de.bund.bfr.jung.JungUtils.java
static Line2D getLineInMiddle(Shape edgeShape) { GeneralPath path = new GeneralPath(edgeShape); float[] seg = new float[6]; List<Point2D> points = new ArrayList<>(); for (PathIterator i = path.getPathIterator(null, 1); !i.isDone(); i.next()) { i.currentSegment(seg);/*from w w w. j a v a2 s . c om*/ points.add(new Point2D.Float(seg[0], seg[1])); } Point2D first = points.get(0); Point2D last = points.get(points.size() - 1); if (first.equals(last)) { Point2D minP = points.stream().min((p1, p2) -> Double.compare(p1.getY(), p2.getY())).get(); return new Line2D.Float(minP, new Point2D.Float((float) (minP.getX() + 1.0), (float) minP.getY())); } else { for (int i = 0; i < points.size() - 1; i++) { Point2D p1 = points.get(i); Point2D p2 = points.get(i + 1); if (p2.distance(last) < p2.distance(first)) { Line2D ortho = getOrthogonal(new Line2D.Float(first, last)); Point2D pp1 = getIntersection(new Line2D.Float(p1, p2), ortho); Point2D pp2 = new Point2D.Float((float) (pp1.getX() + last.getX() - first.getX()), (float) (pp1.getY() + last.getY() - first.getY())); return new Line2D.Float(pp1, pp2); } } return null; } }
From source file:Main.java
/** * Finds the first occurrence of value in <code>double</code> array. */// ww w . j av a 2 s. c o m public static int indexOf(double[] array, double value) { for (int i = 0; i < array.length; i++) { if (Double.compare(array[i], value) == 0) { return i; } } return -1; }
From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java
/** * Get the order of the specified elements in descending or ascending order. * * @param values A vector of double values. * @param indices The indices which will be considered for ordering. * @param descending Flag indicating if we go descending or not. * @return A vector of indices sorted in the provided order. */// w w w . ja v a 2s. co m public static int[] getOrder(double[] values, int[] indices, boolean descending) { // Create an index series: Integer[] opIndices = ArrayUtils.toObject(indices); // Sort indices: Arrays.sort(opIndices, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (descending) { return Double.compare(values[o2], values[o1]); } else { return Double.compare(values[o1], values[o2]); } } }); return ArrayUtils.toPrimitive(opIndices); }
From source file:com.opengamma.analytics.financial.commodity.derivative.CommodityForward.java
@Override public boolean equals(Object obj) { if (this == obj) { return true; }/*ww w . j a v a 2 s . c o m*/ if (obj == null) { return false; } if (!(obj instanceof CommodityForward)) { return false; } final CommodityForward other = (CommodityForward) obj; if (Double.doubleToLongBits(_expiry) != Double.doubleToLongBits(other._expiry)) { return false; } if (!ObjectUtils.equals(_underlying, other._underlying)) { return false; } if (!ObjectUtils.equals(_firstDeliveryDate, other._firstDeliveryDate)) { return false; } if (!ObjectUtils.equals(_lastDeliveryDate, other._lastDeliveryDate)) { return false; } if (!ObjectUtils.equals(_unitName, other._unitName)) { return false; } if (!ObjectUtils.equals(_settlementType, other._settlementType)) { return false; } if (!ObjectUtils.equals(_currency, other._currency)) { return false; } if (Double.compare(_amount, other._amount) != 0) { return false; } if (Double.compare(_unitAmount, other._unitAmount) != 0) { return false; } if (Double.compare(_settlement, other._settlement) != 0) { return false; } if (Double.compare(_referencePrice, other._referencePrice) != 0) { return false; } return true; }
From source file:com.joptimizer.algebra.CholeskySparseFactorization.java
private void doStep(int step) throws Exception { // subtract L[j:n,1:j-n]L[j,1:j-1][T] from S (j=step+1) for (int k = 0; k < step; k++) { int j = step;//just for easy reading double[] LcolumnsValuesK = LcolumnsValues[k]; double LJK = LcolumnsValuesK[j - k];// array of variable dimension (dim-colIndex) if (Double.compare(LJK, 0.) == 0) { continue; }//from w w w .j ava2s. co m // subtract L[j:n,k]*L[k,j][T]=L[j,k]*L[j:n,k] for (int i = j; i < dim; i++) { double LIK = LcolumnsValuesK[i - k];// array of variable dimension (dim-colIndex) double LJKLIK = LJK * LIK; Svalues[i - step] -= LJKLIK; } } // compute L[j:n,j] if (!(Svalues[0] > Utils.getDoubleMachineEpsilon())) { throw new Exception("not positive definite matrix"); } double evStep = Math.sqrt(Svalues[0]); double[] LcolumnsValuesS = new double[dim - step];// max length of SValues LcolumnsValuesS[0] = evStep; for (int i = 1; i < Svalues.length; i++) { double SvaluesR = Svalues[i]; if (Double.compare(SvaluesR, 0.) != 0) { SvaluesR = SvaluesR / evStep; LcolumnsValuesS[i] = SvaluesR; } } LcolumnsValues[step] = LcolumnsValuesS; if (log.isDebugEnabled()) { log.debug("step " + step + " situation:"); log.debug("LcolumnsValues: " + ArrayUtils.toString(LcolumnsValues)); log.debug("Svalues: " + ArrayUtils.toString(Svalues)); } }