到目前为止,我的直觉是一组数字的总和与它们相加的顺序无关。下面,随机数的集合是由seed=0决定的,但是顺序是由线程中的执行顺序决定的。
我想使用来自多线程计算的大量双精度数的总和作为校验和。有没有办法找到一个对总和中的组成数字最敏感但对特定随机加法序列不敏感的和的舍入方案?
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test implements Callable<Double> {
public static class Sum {
double sum = 0;
public synchronized void add(double val) {
sum += val;
}
public double getSum() {
return sum;
}
};
Sum sum;
public Test(Sum sum) {
this.sum = sum;
}
@Override
public Double call() {
Random rand = new Random(0);
for (long i = 0; i < 1000000L; i++) {
sum.add(rand.nextDouble());
}
return 0D;
}
static double mean() {
Sum sum = new Sum();
int cores = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(cores);
ArrayList<Future<Double>> results = new ArrayList<>();
double x = 0;
for (int i = 0; i < cores; i++) {
Test test = new Test(sum);
results.add(pool.submit(test));
}
for (Future<Double> entry : results) {
try {
x += entry.get();
} catch (InterruptedException ex) {
throw new RuntimeException("Thread interrupted.", ex);
} catch (ExecutionException ex) {
throw new RuntimeException("Excecution exception:");
}
}
pool.shutdown();
return sum.getSum();
}
public static void main(String[] args) throws IOException {
for (int i = 0; i < 10; i++) {
System.out.format("Avg:%22.20f\n", mean());
}
}
}