IntegralApproximations.java
A class containing methods to calculate definite integrals and error margins.Supports:
Example: Calculating the integral of sine in [0,pi/2] using 2 strips.
int n = 2; double[] x = new double[n + 1]; double[] y = new double[n + 1]; x[0] = 0.28559933214452704; x[1] = 0.8567979964335803; x[2] = 1.4279966607226338; for (int i = 0; i < n + 1; i++) { y[i] = (double) Math.round(Math.sin(x[i]) * 1000000) / 1000000; } System.out.println("Trapezoidal approximation : " + trapezoidal(x, y)); System.out.println("Simpson approximation : " + simpson(x, y));
Calculating the error
double e1, e2; double[] xe = new double[199]; double[] ye = new double[199]; double start = 0; double dif = x[0] / 198; for (int i = 0; i < 199; i++) { xe[i] = start; start += dif; ye[i] = Math.sin(xe[i]); } e1 = simpson(xe, ye) + simpError(x[0], 198, Math.sin(x[0])); start = x[2]; dif = ((Math.PI / 2) - x[2]) / 198; for (int i = 0; i < 199; i++) { xe[i] = start; start += dif; ye[i] = Math.sin(xe[i]); } e2 = simpson(xe, ye) + simpError(Math.PI / 2 - x[2], 198, 1); System.out.println("Maximum theoretical error (trapezoidal) : " + (e1 + e2 + trapError(x[2] - x[0], n, Math.sin(x[2])))); System.out.println("Actual error (trapezoidal) : " + (1 - trapezoidal(x, y))); System.out.println("Maximum theoretical error (simpson) : " + (e1 + e2 + simpError(x[2] - x[0], n, Math.sin(x[2])))); System.out.println("Actual error (simpson) : " + (1 - simpson(x, y)));
Output
Trapezoidal approximation : 0.7948383637221537 Simpson approximation : 0.8176811695057372 Maximum theoretical error (trapezoidal) : 0.21356634499073798 Actual error (trapezoidal) : 0.20516163627784634 Maximum theoretical error (simpson) : 0.18349059382360064 Actual error (simpson) : 0.18231883049426278
No comments:
Post a Comment