import java.util.function.Function;
public class Integration {
public static void main(String[] args) {
Function<Double, Double> cosine = Math::cos;
double lowerBound = -Math.PI / 2;
double upperBound = -lowerBound;
double delta = 0.01;
System.out.println(integrate(cosine, lowerBound, upperBound, delta));
}
public static double integrate(Function<Double, Double> function, double from, double to, double delta) {
double integral = 0.0;
double x = from;
while (x < to) {
integral += function.apply(x) * delta;
x += delta;
}
return integral;
}
}
1.9999999540410227
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.function.Function;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;
class IntegrationTest {
private Function<Double, Double> cosine;
private double lowerBound;
private double upperBound;
private double delta;
private double expectedIntegral;
@BeforeEach
void setUp() {
// given
cosine = Math::cos;
lowerBound = -Math.PI / 2;
upperBound = -lowerBound;
delta = 0.001;
expectedIntegral = 2.0;
}
@Test
void integrate() {
// when
final double result = Integration.integrate(cosine, lowerBound, upperBound, delta);
// then
assertThat(result, closeTo(expectedIntegral, 0.000001));
}
}