-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegral
More file actions
61 lines (50 loc) · 1.55 KB
/
integral
File metadata and controls
61 lines (50 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.ArrayList;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("int(3x + 2x^2,-1,1)="
+ ParallelIntegral.parallelIntegrate(x -> 3*x + 2*x*x, -1, 1, 8));
}
}
@FunctionalInterface
interface Function {
public double get(double x);
}
class Integral implements Callable<Double> {
Function f;
double a;
double b;
public Integral(Function f, double a, double b) {
this.f = f;
this.a = a;
this.b = b;
}
@Override
public Double call() throws Exception {
double sum = 0;
double rectangeArea = 0;
double delta = (b-a)/100;
for (int i = 1; i <= 100; i++) {
rectangeArea = delta * f.get(a + i*delta) ;
sum += rectangeArea;
}
return sum;
}
}
class ParallelIntegral {
public static double parallelIntegrate(Function f, double a, double b, int k) throws ExecutionException, InterruptedException {
ExecutorService ex = Executors.newFixedThreadPool(k);
ArrayList<Future<Double>> results = new ArrayList<>();
Future<Double> result;
double delta = (b-a)/k;
for (int i = 1 ; i <= k ; i++) {
result = ex.submit(new Integral(f,a + (i-1)*delta, a + i*delta));
results.add(result);
}
double sum = 0;
for (int i = 0 ; i < k ; i++) {
sum += results.get(i).get();
}
return sum;
}
}