本文整理汇总了Java中com.google.common.math.DoubleMath类的典型用法代码示例。如果您正苦于以下问题:Java DoubleMath类的具体用法?Java DoubleMath怎么用?Java DoubleMath使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DoubleMath类属于com.google.common.math包,在下文中一共展示了DoubleMath类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: finish
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Override
public void finish() throws IOException {
final ImmutableMap<Symbol, Double> scores = this.scores.build();
final ImmutableMap<Symbol, Integer> falsePositives = this.falsePositives.build();
final ImmutableMap<Symbol, Integer> truePositives = this.truePositives.build();
final ImmutableMap<Symbol, Integer> falseNegatives = this.falseNegatives.build();
// see guidelines section 7.3.1.1.3 for aggregating rules:
outputDir.mkdirs();
final double meanScore = scores.isEmpty()?Double.NaN:DoubleMath.mean(scores.values());
Files.asCharSink(new File(outputDir, "linearScore.txt"), Charsets.UTF_8)
.write(Double.toString(meanScore));
for (final Symbol queryId : scores.keySet()) {
final File queryDir = new File(outputDir, queryId.asString());
queryDir.mkdirs();
final File queryScoreFile = new File(queryDir, "score.txt");
// avoid dividing by zero
final double normalizer = Math.max(truePositives.get(queryId) + falseNegatives.get(queryId), 1);
// see guidelines referenced above
// pretends that the corpus is a single document
Files.asCharSink(queryScoreFile, Charsets.UTF_8).write(String
.format(SCORE_PATTERN, truePositives.get(queryId), falsePositives.get(queryId),
falseNegatives.get(queryId), 100 * scores.get(queryId) / normalizer));
}
}
示例2: adaptMIPResult
import com.google.common.math.DoubleMath; //导入依赖的package包/类
protected XORAllocation<T> adaptMIPResult(IMIPResult mipResult) {
Map<Bidder<T>, BidderAllocation<T>> trades = new HashMap<>();
for (Bidder<T> bidder : auction.getBidders()) {
double totalValue = 0;
Builder<Good> goodsBuilder = ImmutableSet.<Good>builder();
Builder<XORValue<T>> bundleBids = ImmutableSet.<XORValue<T>>builder();
for (XORValue<T> bundleBid : auction.getBid(bidder).getValues()) {
if (DoubleMath.fuzzyEquals(mipResult.getValue(getBidVariable(bundleBid)), 1, 1e-3)) {
goodsBuilder.addAll(bundleBid.getLicenses());
bundleBids.add(bundleBid);
totalValue += bundleBid.value().doubleValue();
}
}
Set<Good> goods = goodsBuilder.build();
if (!goods.isEmpty()) {
trades.put(bidder, new BidderAllocation<>(totalValue, new Bundle<>(goods), bundleBids.build()));
}
}
return new XORAllocation<>(trades);
}
示例3: getInterval
import com.google.common.math.DoubleMath; //导入依赖的package包/类
/**
* recalculate interval if total number of partitions greater than maximum number of allowed partitions
*
* @param low watermark value
* @param high watermark value
* @param partition interval
* @param Maximum number of allowed partitions
* @return calculated interval
*/
private long getInterval(long lowWatermarkValue, long highWatermarkValue, long partitionInterval, int maxIntervals) {
if (lowWatermarkValue > highWatermarkValue) {
LOG.info("lowWatermarkValue: " + lowWatermarkValue + " is greater than highWatermarkValue: "
+ highWatermarkValue);
return 0;
}
long outputInterval = partitionInterval;
boolean longOverflow = false;
long totalIntervals = Long.MAX_VALUE;
try {
totalIntervals = DoubleMath.roundToLong((double) highWatermarkValue / partitionInterval
- (double) lowWatermarkValue / partitionInterval, RoundingMode.CEILING);
} catch (java.lang.ArithmeticException e) {
longOverflow = true;
}
if (longOverflow || totalIntervals > maxIntervals) {
outputInterval = DoubleMath.roundToLong((double) highWatermarkValue / maxIntervals
- (double) lowWatermarkValue / maxIntervals, RoundingMode.CEILING);
}
return outputInterval;
}
示例4: pack
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Override
public List<WorkUnit> pack(Map<String, List<WorkUnit>> workUnitsByTopic, int numContainers) {
setWorkUnitEstSizes(workUnitsByTopic);
List<WorkUnit> workUnits = Lists.newArrayList();
for (List<WorkUnit> workUnitsForTopic : workUnitsByTopic.values()) {
// For each topic, merge all empty workunits into a single workunit, so that a single
// empty task will be created instead of many.
MultiWorkUnit zeroSizeWorkUnit = new MultiWorkUnit();
for (WorkUnit workUnit : workUnitsForTopic) {
if (DoubleMath.fuzzyEquals(getWorkUnitEstSize(workUnit), 0.0, EPS)) {
addWorkUnitToMultiWorkUnit(workUnit, zeroSizeWorkUnit);
} else {
workUnit.setWatermarkInterval(getWatermarkIntervalFromWorkUnit(workUnit));
workUnits.add(workUnit);
}
}
if (!zeroSizeWorkUnit.getWorkUnits().isEmpty()) {
workUnits.add(squeezeMultiWorkUnit(zeroSizeWorkUnit, state));
}
}
return worstFitDecreasingBinPacking(workUnits, numContainers);
}
示例5: create
import com.google.common.math.DoubleMath; //导入依赖的package包/类
public BufferedImage create(String hash, int size) {
Preconditions.checkArgument(size > 0 && StringUtils.isNotBlank(hash));
boolean[][] array = genartor.getBooleanValueArray(hash);
int ratio = DoubleMath.roundToInt(size / 5.0, RoundingMode.HALF_UP);
BufferedImage identicon = new BufferedImage(ratio * 5, ratio * 5, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = identicon.getGraphics();
graphics.setColor(genartor.getBackgroundColor()); // 背景色
graphics.fillRect(0, 0, identicon.getWidth(), identicon.getHeight());
graphics.setColor(genartor.getForegroundColor()); // 图案前景色
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
if (array[i][j]) {
graphics.fillRect(j * ratio, i * ratio, ratio, ratio);
}
}
}
return identicon;
}
示例6: getEntropyOfRules
import com.google.common.math.DoubleMath; //导入依赖的package包/类
/**
* Return the entropy (unnormalised) of the given rules
*
* @param otherCfg
* @return
*/
public double getEntropyOfRules(final ContextFreeGrammar otherCfg) {
double sum = 0;
for (final Entry<Integer, Multiset<NodeConsequent>> entry : otherCfg.grammar
.entrySet()) {
final int fromNode = entry.getKey();
for (final Multiset.Entry<NodeConsequent> toNodes : entry
.getValue().entrySet()) {
sum += toNodes.getCount()
* DoubleMath.log2(getMLProbability(fromNode,
toNodes.getElement()));
}
}
return sum;
}
示例7: getPosteriorForTree
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Test
public void getPosteriorForTree() {
final FormattedTSGrammar mockGrammar = new FormattedTSGrammar(mock(AbstractJavaTreeExtractor.class));
final BlockCollapsedGibbsSampler sampler = new BlockCollapsedGibbsSampler(10, 10, mockGrammar, mockGrammar);
sampler.addTree(generateSampleTree(), true);
final double geometricProb = 1; // Math.pow(.9, 5) * .1;
final double prior = .25 * geometricProb;
assertEquals(sampler.getSampleGrammar().computeRulePosteriorLog2Probability(generateSampleTree(), true),
DoubleMath.log2(prior), 10E-10);
assertEquals(sampler.getSampleGrammar().computeRulePosteriorLog2Probability(generateSampleTree(), false),
DoubleMath.log2((1. + 10 * prior) / 11), 10E-10);
sampler.lockSamplerData();
assertEquals(sampler.getSampleGrammar().computeRulePosteriorLog2Probability(generateSampleTree(), true),
DoubleMath.log2(prior), 10E-10);
assertEquals(sampler.getSampleGrammar().computeRulePosteriorLog2Probability(generateSampleTree(), false),
DoubleMath.log2((1. + 10 * prior) / 11), 10E-10);
}
示例8: testPriorForTree
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Test
public void testPriorForTree() {
final FormattedTSGrammar mockGrammar = new FormattedTSGrammar(
mock(AbstractJavaTreeExtractor.class));
final CollapsedGibbsSampler sampler = new CollapsedGibbsSampler(10, 10,
mockGrammar, mockGrammar);
sampler.addTree(generateSampleTree(), true);
final double geometricProb = Math.pow(.9, 5) * .1;
assertEquals(
sampler.getPosteriorComputer().getLog2PriorForTree(
generateSampleTree()),
DoubleMath.log2(.25 * geometricProb), 10E-10);
sampler.lockSamplerData();
assertEquals(
sampler.getPosteriorComputer().getLog2PriorForTree(
generateSampleTree()),
DoubleMath.log2(.25 * geometricProb), 10E-10);
}
示例9: testAutocompletion
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Test
public void testAutocompletion() {
final TSGrammar<String> grammar = new TSGrammar<String>();
final ITsgPosteriorProbabilityComputer<String> mlPosteriorComputer = new MlPosteriorComputer(
grammar);
grammar.setPosteriorComputer(mlPosteriorComputer);
grammar.addTree(generateTree());
grammar.addTree(generateRule1());
grammar.addTree(generateRule2());
grammar.addTree(generateRule3());
final TreeProbabilityComputer<String> computer = new TreeProbabilityComputer<String>(
grammar, false, DEFAULT_MATCHER);
assertEquals(computer.getLog2ProbabilityOf(generateTree()),
DoubleMath.log2(3. / 4.), 10E-10);
}
示例10: getLogProbOfSentence
import com.google.common.math.DoubleMath; //导入依赖的package包/类
public double getLogProbOfSentence(final List<String> sentence) {
double logProb = 0;
for (int i = 0; i < sentence.size(); ++i) {
final NGram<String> ngram = NGram.constructNgramAt(i, sentence,
nGramSize);
if (ngram.size() > 1) {
final double prob = getProbabilityFor(ngram);
if (AbstractNGramLM.DEBUG_PROBS) {
LOGGER.info(AbstractNGramLM.getProbString(
trie.substituteWordsToUNK(ngram), prob));
}
checkArgument(prob > 0);
checkArgument(!Double.isInfinite(prob));
logProb += DoubleMath.log2(prob);
}
}
return logProb;
}
示例11: getLogProbOfSentence
import com.google.common.math.DoubleMath; //导入依赖的package包/类
private double getLogProbOfSentence(final List<FullToken> sentence,
final String className) {
final ICache<String> cache = createCache(className);
double logProb = 0;
final List<String> stringToks = Lists.newArrayList();
for (int i = 0; i < sentence.size(); i++) {
stringToks.add(sentence.get(i).token);
}
for (int i = 0; i < sentence.size(); ++i) {
final NGram<String> ngram = NGram.constructNgramAt(i, stringToks,
baseNgram.getN());
if (ngram.size() > 1) {
final double prob = getProbabilityFor(ngram, cache);
checkArgument(prob > 0);
checkArgument(!Double.isInfinite(prob));
logProb += DoubleMath.log2(prob);
}
}
return logProb;
}
示例12: calculateScores
import com.google.common.math.DoubleMath; //导入依赖的package包/类
@Override
public SortedSet<Renaming> calculateScores(
final Multiset<NGram<String>> ngrams,
final Set<String> alternatives, final Scope scope) {
final SortedSet<Renaming> scoreMap = Sets.newTreeSet();
for (final String identifierName : alternatives) {
double score = 0;
for (final Entry<NGram<String>> ngram : ngrams.entrySet()) {
try {
final NGram<String> identNGram = NGram.substituteTokenWith(
ngram.getElement(), WILDCARD_TOKEN, identifierName);
final double ngramScore = scoreNgram(identNGram);
score += DoubleMath.log2(ngramScore) * ngram.getCount();
} catch (final Throwable e) {
LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
}
}
scoreMap.add(new Renaming(identifierName, (addScopePriors(
identifierName, scope) - score) / ngrams.size(), ngrams
.size() / ngramLM.getN(), scope));
}
return scoreMap;
}
示例13: calculateScores
import com.google.common.math.DoubleMath; //导入依赖的package包/类
/**
* Predict the max-likelihood tokens given the ngrams.
*
* @param ngrams
* @param alternatives
* @return
*/
@Override
public SortedSet<Renaming> calculateScores(
final Multiset<NGram<String>> ngrams,
final Set<String> alternatives, final Scope scope) {
final SortedSet<Renaming> suggestions = Sets.newTreeSet();
for (final String alternative : alternatives) {
double score = 0;
for (final NGram<String> ngram : ngrams) {
score += DoubleMath.log2(getNgramLM().getProbabilityFor(
NGram.substituteTokenWith(ngram, WILDCARD_TOKEN,
alternative)));
}
suggestions.add(new Renaming(alternative, -score, 1, null));
}
return suggestions;
}
示例14: equals
import com.google.common.math.DoubleMath; //导入依赖的package包/类
/**
* Check the two input points for equality. This method does not take the
* point number into account.
*
* @param p1 First point to compare
* @param p2 Second point to compare
* @param tolerance The tolerance used for the comparison
* @param altitude Set to true if you want to consider the altitude for the
* comparison
* @return True if they are the same, false otherwise.
*/
public static boolean equals(Point p1, Point p2, double tolerance, boolean altitude) {
if ((p1 == null) || (p2 == null)) {
return false;
}
if (DoubleMath.fuzzyEquals(p1.getEast(), p2.getEast(), tolerance)
&& DoubleMath.fuzzyEquals(p1.getNorth(), p2.getNorth(), tolerance)) {
if (altitude && !MathUtils.isIgnorable(p1.getAltitude())
&& !MathUtils.isIgnorable(p2.getAltitude())) {
if (!DoubleMath.fuzzyEquals(p1.getAltitude(), p2.getAltitude(), tolerance)) {
return false;
}
}
return true;
}
return false;
}
示例15: bestGraphemes
import com.google.common.math.DoubleMath; //导入依赖的package包/类
public List<Alignment> bestGraphemes(Word x, int bestPathCount) {
PathXTable t = new PathXTable(x.unigramCount() + 1, bestPathCount);
t.offer(0, t.make(0, -1, -1));
for (int xx = 1; xx < x.unigramCount() + 1; xx++) {
for (int i = 1; (i <= opts.getMaxXGram()) && (xx - i >= 0); i++) {
String xGram = x.gram(xx - i, i);
double margX = margs.probX(xGram);
double score = DoubleMath.log2(margX) * i;
t.extendPath(xx, xx - i, PathXTable.Entry.sample(score, i));
}
}
return createAlignments(x, t, bestPathCount);
}