How can use Simpsons rule to write a matlab code or java cod
How can use Simpson\'s rule to write a matlab code or java code for below question?
Question:
Find the area when n = 2. I wrote below code by matlab, but I think it is not completely correct.Can you find problem for me ?
f=@(x)(x*sin(x)^2)
format long
a=0
b=3
n=2
dx=(b-a)/n
sum_even = 0;
for i = 1:n/2-1
x(i) = a + 2*i*dx;
sum_even = sum_even + f(x(i));
end
sum_odd = 0;
for i = 1:n/2
x(i) = a + (2*i-1)*dx;
sum_odd = sum_odd + f(x(i));
end
A = dx*(f(a)+ 2*sum_even + 4*sum_odd +f(b))/3
******************************
A=3.01486102991289 (I believe this is wrong)
//A tutor said my code is correct expect the last A equation but he did not said any specific error.//
Solution
Ex-2: solve the equation .
Method -1: =?
>> f=inline(\'x.^2\')
f = Inline function:
f(x) = x.^2
>> Q=quad(f,0,2)
Q = 2.6667
Method -2:
=?
>> f=@(x) x.^2 % ‘.^’ term-by-term exponentiation.
f = @(x)x.^2
>> Q=quad(f,0,2)
Q = 2.6667
Method -3: =?
>> syms x
>> f=x.^2
f = x^2
>> Q=int(f,0,2)
Q = 8/3
Method -4:
>> int(sym(\'x^2\'),0,2)
ans = 8/3
>> eval(ans)
ans = 2.6667
Ex-3: simply the following function
=?
Method -1:
>> f=inline(\'sin(x)\')
f = Inline function:
f(x) = sin(x)
>> Q=quad(f,0,5)
Q = 0.7163
Method -2:
>> f=@(x) sin(x)
f = @(x)sin(x)
>> Q=quad(f,0,5)
Q = 0.7163
Method -3:
>> int(sym(\'sin(x)\'),0,5)
ans = 1 - cos(5)
>> eval(ans)
ans = 0.7163
Ex-4 : =?
Method -1:
>> int(sym(\'sqrt(x)\'),0,2)
ans = (4*2^(1/2))/3
>> eval(ans)
ans = 1.8856
Method -2:
>> f=inline(\'sqrt(x)\')
f = Inline function:
f(x) = sqrt(x)
>> quad(f,0,2)
ans = 1.8856
Method -3:
>> f=@(x) sqrt(x)
f = @(x)sqrt(x)
>> quad(f,0,2)
ans = 1.8856
Ex-5:
5. =?
Method -1:
>> sym x
ans =x
>> f=(\'sqrt(x.^2-(sin(x)).^4)\')
f = sqrt(x.^2-(sin(x)).^4)
>> Q=quad(f,0,2)
Q = 1.5824
Method -2:
>> f=(\'sqrt(x.^2-(sin(x)).^4)\')
f = sqrt(x.^2-(sin(x)).^4)
>> quad(f,0,2)
ans = 1.5824
Method -3:
>> f=@(x) sqrt(x.^2-(sin(x)).^4)
f = @(x)sqrt(x.^2-(sin(x)).^4)
>> quad(f,0,2)
ans = 1.5824
Method -4:
>> f=inline(\'sqrt(x.^2-(sin(x)).^4)\')
f =
Inline function:
f(x) = sqrt(x.^2-(sin(x)).^4)
>> Q=quad(f,0,2)
Q = 1.5824
Method -5:
6. Evaluate .
Method -1:
>> syms x
>> f=(cos(x))^6
f =cos(x)^6
>> int(f,0,pi/2)
ans =(5*pi)/32
>> eval(ans)
ans = 0.4909
Method -2:
>> syms x
>> f=@(x) (cos(x)).^6
f = @(x)(cos(x)).^6
>> Q=quad(f,0,pi/2)
Q = 0.4909
Method -3:
>> syms x
>> f=inline(\'(cos(x)).^6\')
f = Inline function:
f(x) = (cos(x)).^6
>> Q=quad(f,0,pi/2)
Q = 0.4909
Method -4:
>> f=@(x) (cos(x)).^6
f = @(x)(cos(x)).^6
>> Q=quad(f,0,pi/2)
Q = 0.4909
7. Evaluate
Method -1:
>> f=(sin(x))^2*(cos(x))^2
f = cos(x)^2*sin(x)^2
>> int(f)
ans = x/8 - (cos(x)*sin(x))/8 + (cos(x)*sin(x)^3)/4




