1
0
This commit is contained in:
2024-10-07 15:49:51 +03:00
parent de5ca5fa13
commit 110e132711
2 changed files with 14 additions and 31 deletions

View File

@@ -107,27 +107,16 @@ public class IntegralCalculator {
this.callProgressCallback(0, n);
var remainder = n % parallelism;
var partitionSize = n / parallelism;
var currentStart = 0L;
var sum = (function.apply(lowerBound) + function.apply(upperBound)) / 2;
final var futures = new ArrayList<Future<Double>>();
final var total = new AtomicLong(0);
for (var i = 0; i < parallelism; i++) {
final var start = currentStart;
final var end = currentStart + partitionSize + (remainder > 0 ? 1 : 0);
if (remainder > 0)
remainder--;
currentStart = end;
final var order = i;
futures.add(executor.submit(() -> {
var partitionSum = 0.0;
for (var j = start; j < end; j++) {
for (var j = order; j < n; j += parallelism) {
partitionSum += function.apply(lowerBound + h * j);
var progress = total.incrementAndGet();
this.callProgressCallback(progress, n);
this.callProgressCallback(j, n);
}
return partitionSum;

View File

@@ -9,37 +9,31 @@ public class Main {
Function<Double, Double> function = x -> Math.sin(x) * x;
var lowerBound = 0.0;
var upperBound = 1.0;
double[] accuracies = {0.001, 0.00001, 0.0000001, 0.000000001, 0.000000001};
double[] accuracies = {0.0001, 0.00001, 0.0000001, 0.000000001, 0.000000001};
var executor = Executors.newCachedThreadPool();
for (final var accuracy : accuracies) {
var calculator = new IntegralCalculator(
accuracy,
(current, total) -> {
if (current % (total / 15) != 0)
return;
System.out.printf(
"[%s] Progress: %.2f%%%n",
Thread.currentThread().getName(),
(current * 100.0 / total)
);
}
accuracy
);
var startTime = System.nanoTime();
double value = 0;
try {
value = calculator.calculate(function, lowerBound, upperBound, executor, 12);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
value = calculator.calculate(function, lowerBound, upperBound, executor, 1);
} catch (ExecutionException e) {
System.err.println("Error calculating integral: " + e.getMessage());
}
catch (InterruptedException e) {
System.err.println("Thread interrupted: " + e.getMessage());
executor.shutdown();
}
var totalTime = System.nanoTime() - startTime;
System.out.printf(
"[%s] Calculated value: %.15f | Accuracy: %e | Time: %.9fms%n",
Thread.currentThread().getName(),
"Calculated value: %.15f | Accuracy: %e | Time: %.9fms%n",
value,
accuracy,
totalTime / 1_000_000.0