Simpson’s Rule exercise

Approximate the integral [0 10] using Simpson’s Rule N = 10

Solution:

public class Integral {
public static void main(String[] args) {
	
	float a = 0.0f; // lower Bound
	float b = 10.0f; // high Bound
	int N = 10; // define N
	float x[] = new float[N+1]; // reservation for last and first value
	//calculate x_i 
	
	x[0] = a;
	
	x[N] = b;
	
	float solution =  x[0]*x[0] + x[N]*x[N];
	float function = 1;
	float h = (b-a)/(N*3);
	
	for(int i = 1;i<=x.length-2;i++) {
		
		x[i] = (a + i*(b-a)/N)  *   (a + i*(b-a)/N) ; // function of x^2 = x*x
		
		if(i%2 == 0) {
			solution += 2*x[i];
		}else {
			solution += 4*x[i];
		}
		//System.out.println(x[i]);
		
		  
		
	}
	System.out.printf("%.2f",solution*h); // In conclusion we make an output 
	}
}

Solution: 333,33

Download source code:

Integral

Leave a Reply

Your email address will not be published. Required fields are marked *