@Override public Double integrate(Function<Double, Double> f, Double lower, Double upper) { ArgChecker.notNull(f, "f"); ArgChecker.notNull(lower, "lower bound"); ArgChecker.notNull(upper, "upper bound"); try { if (lower < upper) { return integration(f, lower, upper); } log.info("Upper bound was less than lower bound; swapping bounds and negating result"); return -integration(f, upper, lower); } catch (Exception e) { throw new IllegalStateException("function evaluation returned NaN or Inf"); } }
private double integrationRec(Function<Double, Double> f, double lower, double upper, double res, double counter) { double localTol = gain * tol; double half = 0.5 * (lower + upper); double newResDw = integrator.integrate(f, lower, half); double newResUp = integrator.integrate(f, half, upper); double newRes = newResUp + newResDw; if (Math.abs(res - newRes) < localTol || counter == 0 || (Math.abs(res) < 1.e-14 && Math.abs(newResUp) < 1.e-14 && Math.abs(newResDw) < 1.e-14)) { return newRes + (newRes - res) / gain; } return integrationRec(f, lower, half, newResDw, counter - 1) + integrationRec(f, half, upper, newResUp, counter - 1); }
/** * */ @Test public void equalsHashCodetest() { final Integrator1D<Double, Double> integBase = new SimpsonIntegrator1D(); final Integrator1D<Double, Double> integ0 = new AdaptiveCompositeIntegrator1D(integBase); final Integrator1D<Double, Double> integ1 = new AdaptiveCompositeIntegrator1D(integBase); final Integrator1D<Double, Double> integ2 = new AdaptiveCompositeIntegrator1D(new RungeKuttaIntegrator1D()); final Integrator1D<Double, Double> integ3 = new AdaptiveCompositeIntegrator1D(integBase, 1., 1.e-5); final Integrator1D<Double, Double> integ4 = new AdaptiveCompositeIntegrator1D(integBase, 2., 1.e-5); final Integrator1D<Double, Double> integ5 = new AdaptiveCompositeIntegrator1D(integBase, 1., 1.e-6); assertTrue(integ0.equals(integ0)); assertTrue(integ0.equals(integ1)); assertTrue(integ1.equals(integ0)); assertTrue(integ1.hashCode() == integ0.hashCode()); assertTrue(!(integ0.equals(integ2))); assertTrue(!(integ0.equals(integ3))); assertTrue(!(integ0.equals(integ4))); assertTrue(!(integ0.equals(integ5))); assertTrue(!(integ0.equals(integBase))); assertTrue(!(integ0.equals(null))); assertTrue(!(integ3.equals(integ5))); assertTrue(!(integ1.hashCode() == INTEGRATOR.hashCode())); } }
/** * */ @Test public void sampleDataTest() { final Integrator1D<Double, Double> localInt = new AdaptiveCompositeIntegrator1D(new SimpsonIntegrator1D(), 10., 1.e-4); assertEquals(-0.368924186060527, localInt.integrate(sampleFunc(), 1.1, 3.), 1.e-6); // answer from quadpack }
private Double integration(Function<Double, Double> f, Double lower, Double upper) { double res = integrator.integrate(f, lower, upper); return integrationRec(f, lower, upper, res, MAX_IT); }