當前位置: 首頁>>代碼示例>>Java>>正文


Java LongMath類代碼示例

本文整理匯總了Java中com.google.common.math.LongMath的典型用法代碼示例。如果您正苦於以下問題:Java LongMath類的具體用法?Java LongMath怎麽用?Java LongMath使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


LongMath類屬於com.google.common.math包,在下文中一共展示了LongMath類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: bitsForNumElementsWithLoadFactor

import com.google.common.math.LongMath; //導入依賴的package包/類
static int bitsForNumElementsWithLoadFactor(long numElements) {
    if (numElements == 0) {
        return 1;
    }

    int candidateBits = Long.bitCount(numElements) == 1 ?
            Math.max(1, Long.numberOfTrailingZeros(numElements)) :
            Long.numberOfTrailingZeros(Long.highestOneBit(numElements) << 1L);

    //May need an extra bit due to load factor
    if (((long) (LongMath.pow(2, candidateBits) * 0.75)) < numElements) {
        candidateBits++;
    }

    return candidateBits;
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:17,代碼來源:QuotientFilter.java

示例2: concat

import com.google.common.math.LongMath; //導入依賴的package包/類
/**
 * Returns a {@link Stream} containing the elements of the first stream, followed by the elements
 * of the second stream, and so on.
 *
 * <p>This is equivalent to {@code Stream.of(streams).flatMap(stream -> stream)}, but the returned
 * stream may perform better.
 *
 * @see Stream#concat(Stream, Stream)
 */
@SafeVarargs
public static <T> Stream<T> concat(Stream<? extends T>... streams) {
  // TODO(lowasser): consider an implementation that can support SUBSIZED
  boolean isParallel = false;
  int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL;
  long estimatedSize = 0L;
  ImmutableList.Builder<Spliterator<? extends T>> splitrsBuilder =
      new ImmutableList.Builder<>(streams.length);
  for (Stream<? extends T> stream : streams) {
    isParallel |= stream.isParallel();
    Spliterator<? extends T> splitr = stream.spliterator();
    splitrsBuilder.add(splitr);
    characteristics &= splitr.characteristics();
    estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize());
  }
  return StreamSupport.stream(
      CollectSpliterators.flatMap(
          splitrsBuilder.build().spliterator(),
          splitr -> (Spliterator<T>) splitr,
          characteristics,
          estimatedSize),
      isParallel);
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:33,代碼來源:Streams.java

示例3: IdGenerator

import com.google.common.math.LongMath; //導入依賴的package包/類
/**
 * @param alphabet the alphabet of legal characters for IDs generated by this generator
 * @param perturb whether or not to perturb generated IDs by a random perturbation to avoid
 *                collisions in distributed key generation. Pass {@code false} if this generator
 *                is used to generate a sort key that is a secondary key where ordering
 *                conflicts can be deterministically resolved by the primary key. This setting
 *                only applies to the {@code generate...} methods.
 */
public IdGenerator(IdAlphabet alphabet, boolean perturb) {
    mAlphabet = alphabet;
    mPerturb = perturb;

    // Find the maximum number of digits we'd need to encode an unsigned long if the radix were
    // uniform for the entire string.
    // ceil(log_RADIX(Long.MAX + 1))
    mLongUniformRadixLength = (int) Math.ceil(LOG_LONG / Math.log(alphabet.radix()));
    mMostSignificantUnit = LongMath.pow(alphabet.radix(), mLongUniformRadixLength - 1);

    mMaxSafeMostSignificantDigit = (int) (Long.MAX_VALUE / mMostSignificantUnit);
    mMaxSafeMostSignificantValue = mMaxSafeMostSignificantDigit * mMostSignificantUnit;

    // The first character may have additional restrictions, so we have less chars to work with
    // for the first digit. If we still have enough digits, we'll proceed and just use a special
    // mapping for the leading digit. Otherwise, we'll pad by a leading zero, thus making the
    // remaining encoding the common case.

    // So, what most-significant digit do we need to encode the max unsigned value?
    PartialDivisionResult div = transformToSignedDivision(-1);
    int maxMostSignficantDigit = div.partialMostSignificantDigit +
            (int) (div.partialRemainder / mMostSignificantUnit);
    mLongEncodedLength = maxMostSignficantDigit < alphabet.leadingRadix() ?
            mLongUniformRadixLength : mLongUniformRadixLength + 1;
}
 
開發者ID:vanadium-archive,項目名稱:todos,代碼行數:34,代碼來源:IdGenerator.java

示例4: toL

import com.google.common.math.LongMath; //導入依賴的package包/類
private static Long toL(String value) {
	if (null == value) {
		return 0L;
	}
	
	int idxSep = value.indexOf(SEPARATOR_CHAR);
	if (idxSep > -1) {
		value = value.substring(idxSep + 1);
	}
	
	long r = 0;
	int length = value.length();
	for (int i = 0; i < length; i++) {
		long val = LongMath.pow(RADIX, (length - i - 1));
		char c = value.charAt(i);
		int tmp = KEYS.indexOf(c);
		r += (tmp * val);
	}

	return r;
}
 
開發者ID:jronrun,項目名稱:benayn,代碼行數:22,代碼來源:Scale62.java

示例5: reserveEarliestAvailable

import com.google.common.math.LongMath; //導入依賴的package包/類
@Override
final long reserveEarliestAvailable(int requiredPermits, long nowMicros) {
  resync(nowMicros);
  long returnValue = nextFreeTicketMicros;
  double storedPermitsToSpend = min(requiredPermits, this.storedPermits);
  double freshPermits = requiredPermits - storedPermitsToSpend;
  long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend)
      + (long) (freshPermits * stableIntervalMicros);

  try {
    this.nextFreeTicketMicros = LongMath.checkedAdd(nextFreeTicketMicros, waitMicros);
  } catch (ArithmeticException e) {
    this.nextFreeTicketMicros = Long.MAX_VALUE;
  }
  this.storedPermits -= storedPermitsToSpend;
  return returnValue;
}
 
開發者ID:sander120786,項目名稱:guava-libraries,代碼行數:18,代碼來源:SmoothRateLimiter.java

示例6: incrementMisReplicatedIndex

import com.google.common.math.LongMath; //導入依賴的package包/類
public static Long incrementMisReplicatedIndex(final int increment)
    throws IOException {
  return (Long) new LightWeightRequestHandler(
      HDFSOperationType.INCREMENT_MIS_REPLICATED_FILES_INDEX) {
    @Override
    public Object performTask() throws IOException {

      return handleVariableWithWriteLock(new Handler() {
        @Override
        public Object handle(VariableDataAccess<Variable, Variable.Finder> vd)
            throws StorageException {
          LongVariable var = (LongVariable) vd
              .getVariable(Variable.Finder.MisReplicatedFilesIndex);
          long oldValue = var == null ? 0 : var.getValue();
          long newValue = increment == 0 ? 0 : LongMath.checkedAdd
              (oldValue, increment);
          vd.setVariable(new LongVariable(Variable.Finder.MisReplicatedFilesIndex,
              newValue));
          return newValue;
        }
      });
    }
  }.handle();
}
 
開發者ID:hopshadoop,項目名稱:hops,代碼行數:25,代碼來源:HdfsVariables.java

示例7: expandPower

import com.google.common.math.LongMath; //導入依賴的package包/類
/**
 * Expand a polynomial power with the multinomial theorem. See
 * <a href= "http://en.wikipedia.org/wiki/Multinomial_theorem">Wikipedia - Multinomial theorem</a>
 * 
 * @param plusAST
 * @param n
 *            <code>n &ge; 0</code>
 * @return
 */
private IExpr expandPower(final IAST plusAST, final int n) {
	if (n == 1) {
		IExpr temp = expandPlus(plusAST);
		if (temp.isPresent()) {
			return temp;
		}
		addExpanded(plusAST);
		return plusAST;
	}
	if (n == 0) {
		return F.C1;
	}

	int k = plusAST.argSize();
	long numberOfTerms = LongMath.binomial(n + k - 1, n);
	if (numberOfTerms > Integer.MAX_VALUE) {
		throw new ArithmeticException("");
	}
	final IASTAppendable expandedResult = F.ast(F.Plus, (int) numberOfTerms, false);
	Expand.NumberPartititon part = new Expand.NumberPartititon(plusAST, n, expandedResult);
	part.partition();
	return PlusOp.plus(expandedResult);
}
 
開發者ID:axkr,項目名稱:symja_android_library,代碼行數:33,代碼來源:Algebra.java

示例8: loadPartialY

import com.google.common.math.LongMath; //導入依賴的package包/類
public static LongObjectMap<float[]> loadPartialY(int partition,
                                                int numPartitions,
                                                String prefix,
                                                Configuration conf) throws IOException {
  LongObjectMap<float[]> result = new LongObjectMap<float[]>();
  AvroFileSource<MatrixRow> records = new AvroFileSource<MatrixRow>(
      Namespaces.toPath(prefix),
      (AvroType<MatrixRow>) ALSTypes.DENSE_ROW_MATRIX);
  for (MatrixRow record : records.read(conf)) {
    long id = record.getRowId();
    if (LongMath.mod(id, numPartitions) == partition) {
      result.put(id, record.getValues());
    }
  }
  return result;
}
 
開發者ID:apsaltis,項目名稱:oryx,代碼行數:17,代碼來源:ComputationDataUtils.java

示例9: getBytes

import com.google.common.math.LongMath; //導入依賴的package包/類
protected static byte[] getBytes(long sum, int arraySize) {
    final byte[] b = new byte[arraySize];
    for (int i = 0; i < b.length; i++) {
        final int reverseIndex = b.length - 1 - i;
        final long factor = LongMath.pow(256, reverseIndex);
        final long base = sum / factor;
        b[i] = UnsignedBytes.checkedCast(base);
        sum = sum - (base * factor);
    }
    return b;
}
 
開發者ID:kaspersorensen,項目名稱:kafka-record-updater,代碼行數:12,代碼來源:SegmentFileUpdater.java

示例10: getLong

import com.google.common.math.LongMath; //導入依賴的package包/類
protected static long getLong(byte[] b) {
    long sum = 0;
    for (int i = 0; i < b.length; i++) {
        final int reverseIndex = b.length - 1 - i;
        final long factor = LongMath.pow(256, reverseIndex);
        final int base = UnsignedBytes.toInt(b[i]);
        sum += base * factor;
    }
    return sum;
}
 
開發者ID:kaspersorensen,項目名稱:kafka-record-updater,代碼行數:11,代碼來源:SegmentFileUpdater.java

示例11: reserveEarliestAvailable

import com.google.common.math.LongMath; //導入依賴的package包/類
@Override
final long reserveEarliestAvailable(int requiredPermits, long nowMicros) {
  resync(nowMicros);
  long returnValue = nextFreeTicketMicros;
  double storedPermitsToSpend = min(requiredPermits, this.storedPermits);
  double freshPermits = requiredPermits - storedPermitsToSpend;
  long waitMicros =
      storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend)
          + (long) (freshPermits * stableIntervalMicros);

  this.nextFreeTicketMicros = LongMath.saturatedAdd(nextFreeTicketMicros, waitMicros);
  this.storedPermits -= storedPermitsToSpend;
  return returnValue;
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:15,代碼來源:SmoothRateLimiter.java

示例12: testBitSize

import com.google.common.math.LongMath; //導入依賴的package包/類
@AndroidIncompatible // slow
public void testBitSize() {
  double fpp = 0.03;
  for (int i = 1; i < 10000; i++) {
    long numBits = BloomFilter.optimalNumOfBits(i, fpp);
    int arraySize = Ints.checkedCast(LongMath.divide(numBits, 64, RoundingMode.CEILING));
    assertEquals(
        arraySize * Long.SIZE,
        BloomFilter.create(Funnels.unencodedCharsFunnel(), i, fpp).bitSize());
  }
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:12,代碼來源:BloomFilterTest.java

示例13: run

import com.google.common.math.LongMath; //導入依賴的package包/類
public static void run() throws Exception {
  Job job = new JobDetail(); // 創建Job
  executorService = Executors.newFixedThreadPool(N_THRESHOLDS); // 新建固定大小線程的池子
  for (int i = 0; i < N_THRESHOLDS; i++) {
    executorService.submit(new Worker(job)); // 提交線程到池子中
  }
  // 還需要一個線程,用於周期檢查執行時間是否到達
  final ScheduledExecutorService scheduledExcutor = Executors.newSingleThreadScheduledExecutor();
  scheduledExcutor.scheduleAtFixedRate(new Runnable() {
    public void run() {
      if (totalTime.decrementAndGet() == 0) { // 執行時間遞減到0
        runnning = false; // 告訴線程,時間到了,所有線程不再執行
        scheduledExcutor.shutdownNow();
      }
    }
  }, 1L, 1L, TimeUnit.SECONDS);

  // 主線程等到所有的線程都退出,則開始統計
  countDownLatch.await();

  long totalExeCount = totalExecCount.get();
  System.out.println(N_THRESHOLDS + " 個線程," + TIME_THRESHOLDS + " 秒內總共執行的事物數量:" + totalExeCount);

  long tps = LongMath.divide(totalExeCount, TIME_THRESHOLDS, RoundingMode.HALF_EVEN);

  System.out.println("OKHttp執行的TPS: " + tps);

  executorService.shutdownNow(); // 關閉線程池


}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:32,代碼來源:TpsWorkbeanch.java

示例14: evaluate

import com.google.common.math.LongMath; //導入依賴的package包/類
@Override
public Long evaluate(Input<Integer>... args) {
    long millis = DateTimeUtils.currentTimeMillis();
    if (args.length == 1) {
        Integer precision = args[0].value();
        if (precision == null) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "NULL precision not supported for %s", NAME));
        }
        int factor;
        switch (precision) {
            case 0:
                factor = 1000;
                break;
            case 1:
                factor = 100;
                break;
            case 2:
                factor = 10;
                break;
            case 3:
                factor = 1;
                break;
            default:
                throw new IllegalArgumentException("Precision must be between 0 and 3");
        }
        millis = LongMath.divide(millis, factor, RoundingMode.DOWN) * factor;
    }
    return millis;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:31,代碼來源:CurrentTimestampFunction.java

示例15: kCombinationCount

import com.google.common.math.LongMath; //導入依賴的package包/類
public static long kCombinationCount(int n, int k) {
    long result;
    if(k > n) {
        result = 0;
    } else {
      //result = LongMath.factorial(n) / LongMath.factorial(n - k);

//The formula below should be equal to the one above
        long combinationCount = LongMath.binomial(n, k);
        long permutationCount = LongMath.factorial(k);
        result = combinationCount * permutationCount;
    }
    return result;
}
 
開發者ID:SmartDataAnalytics,項目名稱:SubgraphIsomorphismIndex,代碼行數:15,代碼來源:ProblemMappingKPermutationsOfN.java


注:本文中的com.google.common.math.LongMath類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。