java.util.stream.DoubleStream.average()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(8.1k)|赞(0)|评价(0)|浏览(264)

本文整理了Java中java.util.stream.DoubleStream.average()方法的一些代码示例,展示了DoubleStream.average()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。DoubleStream.average()方法的具体详情如下:
包路径:java.util.stream.DoubleStream
类名称:DoubleStream
方法名:average

DoubleStream.average介绍

[英]Returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. If any recorded value is a NaN or the sum is at any point a NaN then the average will be NaN.

The average returned can vary depending upon the order in which values are recorded. This method may be implemented using compensated summation or other technique to reduce the error bound in the #sum used to compute the average.

The average is a special case of a reduction.

This is a terminal operation.
[中]返回描述此流元素算术平均值的OptionalDouble,如果此流为空,则返回空可选值。如果任何记录值为NaN或任何点的总和为NaN,则平均值为NaN。
返回的平均值可能因记录值的顺序而异。该方法可以使用补偿求和或其他技术来实现,以减少用于计算平均值的#和中的误差范围。
平均值是reduction的一个特例。
这是一个terminal operation

代码示例

代码示例来源:origin: apache/ignite

/**
 * Gets the the average value of best score array.
 *
 * @return The value.
 */
public double getBestAvgScore() {
  if (bestScore == null)
    return Double.MIN_VALUE;
  return Arrays.stream(bestScore).average().orElse(Double.MIN_VALUE);
}

代码示例来源:origin: prestodb/presto

private int getNewTaskCount()
{
  if (scheduledNodes.isEmpty()) {
    return 1;
  }
  double fullTasks = sourceTasksProvider.get().stream()
      .filter(task -> !task.getState().isDone())
      .map(TaskStatus::isOutputBufferOverutilized)
      .mapToDouble(full -> full ? 1.0 : 0.0)
      .average().orElse(0.0);
  long writtenBytes = writerTasksProvider.get().stream()
      .map(TaskStatus::getPhysicalWrittenDataSize)
      .mapToLong(DataSize::toBytes)
      .sum();
  if ((fullTasks >= 0.5) && (writtenBytes >= (writerMinSizeBytes * scheduledNodes.size()))) {
    return 1;
  }
  return 0;
}

代码示例来源:origin: speedment/speedment

default OptionalDouble average(DoublePipeline pipeline) {
  requireNonNull(pipeline);
  return optimize(pipeline).getAsDoubleStream().average();
}

代码示例来源:origin: apache/storm

private Scope transition(LoadMapping load) {
  List<Integer> targetInScope = getTargetsInScope(currentScope);
  if (targetInScope.isEmpty()) {
    Scope upScope = Scope.upgrade(currentScope);
    if (upScope == currentScope) {
      throw new RuntimeException("The current scope " + currentScope + " has no target tasks.");
    }
    currentScope = upScope;
    return transition(load);
  }
  if (null == load) {
    return currentScope;
  }
  double avg = targetInScope.stream().mapToDouble((key) -> load.get(key)).average().getAsDouble();
  Scope nextScope;
  if (avg < lowerBound) {
    nextScope = Scope.downgrade(currentScope);
    if (getTargetsInScope(nextScope).isEmpty()) {
      nextScope = currentScope;
    }
  } else if (avg > higherBound) {
    nextScope = Scope.upgrade(currentScope);
  } else {
    nextScope = currentScope;
  }
  return nextScope;
}

代码示例来源:origin: OryxProject/oryx

return (clusterScatter1 + clusterScatter2) / distanceFn.applyAsDouble(centerI, centerJ);
 }).max().orElse(0.0);
}).average().orElse(0.0);

代码示例来源:origin: apache/ignite

final double locAvgScore = Arrays.stream(locScores).average().orElse(Double.MIN_VALUE);

代码示例来源:origin: google/guava

public void testEquivalentStreams() {
 // For datasets of many double values created from an array, we test many combinations of finite
 // and non-finite values:
 for (ManyValues values : ALL_MANY_VALUES) {
  double[] array = values.asArray();
  Stats stats = Stats.of(array);
  // instance methods on Stats vs on instance methods on DoubleStream
  assertThat(stats.count()).isEqualTo(stream(array).count());
  assertEquivalent(stats.mean(), stream(array).average().getAsDouble());
  assertEquivalent(stats.sum(), stream(array).sum());
  assertEquivalent(stats.max(), stream(array).max().getAsDouble());
  assertEquivalent(stats.min(), stream(array).min().getAsDouble());
  // static method on Stats vs on instance method on DoubleStream
  assertEquivalent(Stats.meanOf(array), stream(array).average().getAsDouble());
  // instance methods on Stats vs instance methods on DoubleSummaryStatistics
  DoubleSummaryStatistics streamStats = stream(array).summaryStatistics();
  assertThat(stats.count()).isEqualTo(streamStats.getCount());
  assertEquivalent(stats.mean(), streamStats.getAverage());
  assertEquivalent(stats.sum(), streamStats.getSum());
  assertEquivalent(stats.max(), streamStats.getMax());
  assertEquivalent(stats.min(), streamStats.getMin());
 }
}

代码示例来源:origin: org.apache.poi/poi

double avg = Arrays.stream(y).average().orElse(0);
for(int i = 0; i < result.length; i++) result[i] = avg;
return new TrendResults(result, resultWidth, resultHeight);

代码示例来源:origin: aol/cyclops

default double stdDeviation(ToDoubleFunction<T> fn){
  Seq<T> list = stream().seq();
  double avg = list.collect(Collectors.<T>averagingDouble(fn));
  return Math.sqrt( list.stream().mapToDouble(fn)
      .map(i->i-avg)
      .map(i->i*i)
      .average()
      .getAsDouble());
}

代码示例来源:origin: io.github.msdk/msdk-datamodel

/** {@inheritDoc} */
@Override
public Float getRT() {
 synchronized (features) {
  Collection<Feature> allFeatures = features.values();
  float averageRt = (float) allFeatures.stream().mapToDouble(Feature::getRetentionTime)
    .average().getAsDouble();
  return averageRt;
 }
}

代码示例来源:origin: com.shazam.chimprunner/chimprunner

@Override
  public void endOverall() {
    double average = timings.stream()
        .mapToDouble(t -> t)
        .average()
        .getAsDouble();
    resultsMap.put(testCaseEvent, average);
    logger.info("Average time: " + average);
  }
}

代码示例来源:origin: dstl/baleen

@Override
 public Optional<Number> aggregate(List<? extends Number> values) {
  if (CollectionUtils.isEmpty(values)) {
   return Optional.empty();
  }
  return Optional.of(values.stream().mapToDouble(Number::doubleValue).average().getAsDouble());
 }
}

代码示例来源:origin: se.ugli.ugli-commons/ugli-commons

@Override
public OptionalDouble average() {
  // This is a terminal operation
  return evalAndclose(() -> stream.average());
}

代码示例来源:origin: Rsl1122/Plan-PlayerAnalytics

public double averageTPS() {
  return tpsData.stream()
      .mapToDouble(TPS::getTicksPerSecond)
      .filter(num -> num >= 0)
      .average().orElse(-1);
}

代码示例来源:origin: org.ranksys/JavaFM

@Override
public double error(FM fm, FMData test) {
  return test.stream()
      .mapToDouble(x -> error.error(fm, x))
      .average().getAsDouble();
}

代码示例来源:origin: org.ranksys/JavaFM

@Override
public double error(FM fm, ListWiseFMData test) {
  return test.streamByGroup().map(Entry::getValue)
      .mapToDouble((List<? extends FMInstance> group) -> {
        double[] p = getP(group);
        double[] q = getQ(fm, group);
        return IntStream.range(0, group.size())
            .mapToDouble(i -> -p[i] * log(q[i]))
            .sum();
      })
      .average().getAsDouble();
}

代码示例来源:origin: cheng-li/pyramid

@Deprecated
public static double overlap(MultiLabel[] multiLabels, MultiLabel[] predictions){
  return IntStream.range(0,multiLabels.length).parallel()
      .mapToDouble(i -> overlap(multiLabels[i],predictions[i]))
      .average().getAsDouble();
}

代码示例来源:origin: com.aol.cyclops/cyclops-streams

/**
 * Perform an asynchronous average operation
 * @see java.util.stream.Stream#mapToDouble(ToDoubleFunction)
 *      @see java.util.stream.DoubleStream#average()
 * */
default CompletableFuture<OptionalDouble> averageDouble(ToDoubleFunction<? super T> fn){
  
  return CompletableFuture.supplyAsync(()->getStream()
              .flatMapToDouble(t-> DoubleStream.of(fn.applyAsDouble(t)))
              .average(),getExec());
      
}
/**

代码示例来源:origin: pravega/pravega

private void outputStats(String indexName, String statsName, Function<PerfResult, Long> statsProvider, Collection<PerfResult> results) {
  double min = results.stream().mapToDouble(r -> statsProvider.apply(r) / (double) r.count).min().orElse(-1) / NANOS_TO_MILLIS;
  double max = results.stream().mapToDouble(r -> statsProvider.apply(r) / (double) r.count).max().orElse(-1) / NANOS_TO_MILLIS;
  double avg = results.stream().mapToDouble(r -> statsProvider.apply(r) / (double) r.count).average().orElse(-1) / NANOS_TO_MILLIS;
  System.out.println(String.format("%s.%s: Min = %.2f us, Max = %.2f us, Avg = %.2f us", indexName, statsName, min, max, avg));
}

代码示例来源:origin: cheng-li/pyramid

public static double instanceMAP(MultiLabelClassifier.AssignmentProbEstimator classifier, MultiLabelClfDataSet dataSet, List<MultiLabel> combinations){
  return IntStream.range(0, dataSet.getNumDataPoints()).parallel().mapToDouble(i->{
    int[] binaryLabels = new int[classifier.getNumClasses()];
    MultiLabel multiLabel = dataSet.getMultiLabels()[i];
    for (int l:multiLabel.getMatchedLabels()) {
      binaryLabels[l] = 1;
    }
    double[] comProbs = classifier.predictAssignmentProbs(dataSet.getRow(i),combinations);
    double[] probs = Utils.marginals(combinations, comProbs, classifier.getNumClasses());
    return AveragePrecision.averagePrecision(binaryLabels, probs);
  }).average().getAsDouble();
}

相关文章