-
Notifications
You must be signed in to change notification settings - Fork 3
/
IntegrateFunction.groovy
87 lines (67 loc) · 2.23 KB
/
IntegrateFunction.groovy
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import groovy.transform.CompileStatic;
import java.util.function.DoubleUnaryOperator;
import java.util.concurrent.atomic.AtomicInteger;
@CompileStatic
trait IntegralUnaryFunction {
abstract double integrate(int steps, double start, double end);
public double delta(final int steps, final double start, final double end) {
return Math.abs(end - start) / (double) steps;
}
static class Runner extends RunnableState {
final IntegralUnaryFunction iuf;
final int steps;
final double start;
final double end;
Runner(final IntegralUnaryFunction iuf, final int steps, final double start, final double end) {
this.iuf = iuf;
this.steps = steps;
this.start = start;
this.end = end;
}
double _state;
public Object getState() { return _state; }
public void run() {
_state = iuf.integrate(steps, start, end);
}
}
public RunnableState runner(final int steps, final double start, final double end) {
return new Runner(this, steps, start, end);
}
}
class SlowRectangular implements IntegralUnaryFunction {
final DoubleUnaryOperator op;
SlowRectangular(final DoubleUnaryOperator op) {
this.op = op;
}
double integrate(final int steps, final double start, final double end) {
double d = delta(steps, start, end);
int count = 0;
double total = 0.0d;
double xValue = start;
while(count < steps) {
total += (d * op.applyAsDouble(xValue));
++count;
xValue += d;
}
return total;
}
}
@CompileStatic
class FastRectangular implements IntegralUnaryFunction {
final DoubleUnaryOperator op;
FastRectangular(final DoubleUnaryOperator op) {
this.op = op;
}
double integrate(final int steps, final double start, final double end) {
double d = delta(steps, start, end);
int count = 0;
double total = 0.0d;
double xValue = start;
while(count < steps) {
total += (d * op.applyAsDouble(xValue));
++count;
xValue += d;
}
return total;
}
}