# Summing using simspons rule for a given range

17 views (last 30 days)
Oliver Wilson on 9 Apr 2021 at 15:13
Answered: John D'Errico on 9 Apr 2021 at 17:33
I am aiming to use a composite simpsons rule on a function but am only interested in summing in when that function is less then a given value eg y = 10
function S=simpson_rule(f,x,dn)
while (f(x)>10)
f(x) = 0
end
h=(x(2)-x(1))/(2*dn); % finding column width
s1=0; %initialising series values
s2=0;
f1 = f(x(1)); %value of function at start
f2 = f(x(2)); %value of function at end
for k=1:dn % odd series
xa=x(1)+h*(2*k-1);
s1=s1+f(xa);
end
for k=1:(dn-1) %even series
xb=x(1)+h*2*k;
s2=s2+f(xb);
end
S=h*(f1+f2+4*s1+2*s2)/3; %simpsons rule formula based on https://slideplayer.com/slide/15091553/
This what ive got but it still sums values higher then y = 10

VBBV on 9 Apr 2021 at 15:35
%f true
if f(x)>10
f(x) = 0
else
... % rest of code
end
Try this
##### 2 CommentsShowHide 1 older comment
John D'Errico on 9 Apr 2021 at 17:20
This won't work, at least because it is not even valid MATLAB code. f(x)=0 is NOT a valid way to assign a value in MATLAB.

John D'Errico on 9 Apr 2021 at 17:33
If I might suggest, your goal is actively a poor one. Why?
Simpson's rule is a higher order rule. It tries to give you a higher degree of accuracy. However, the idea of introducing what is essentially multiple points of non-differentiability into your function will kill any gains you would have achieved using the higher order nature of Simpson's rule. There is simply no purpose in using Simpson's rule on a function that is not well behaved to gain from the higher order.
So first, just use trapezoidal rule.
Next, are you asking to sum only the part of your function value that does not exceed 10? That is, if the function is larger than 10, will you just use 10 at that point? Or will you not integrate at all over any region where the function value is greater than 10? These two are VERY different goals, and will have very different results.