Untitled
unknown
java
2 years ago
1.6 kB
7
Indexable
import java.util.function.Function; import java.util.function.Supplier; public class IntegratorSimpson implements Supplier<Double> { private final Function<Double, Double> function; private final double a, b; private final double accuracy; public IntegratorSimpson(Function<Double, Double> function, double a, double b, double accuracy) { this.function = function; this.a = a; this.b = b; this.accuracy = accuracy; } @Override public Double get() { double dx = b - a; double olds = 0; var f = function; double oldt = 0.5 * (f.apply(a) + f.apply(b)) * dx; for (int i = 1; ; i *= 2) { double t = 0; double spacing = dx / i; double x = a + 0.5 * spacing; for (int q = 0; q < i; q++) { t += f.apply(x); x += spacing; } t = 0.5 * (olds + t * spacing); double s = (4 * t - oldt) / 3; if (Math.abs(s - olds) <= accuracy) return s; olds = s; oldt = t; } } public static void main(String[] args) { assert Math.pow(10, -5) == 1E-5; IntegratorSimpson simpson = new IntegratorSimpson( x -> Math.exp(x) * Math.cos(x), 0, 1, 1E-5 * 0.5); System.out.println(simpson.get()); } }
Editor is loading...
Leave a Comment