2 functions that should do the same but gives different results

9 views (last 30 days)
So we have an assignement where we are going to use the simpson rule to calculate the integral of a function, I am a beginner at matlab just fyi I got these 2
for i=1:2:n
summa=summa+(f(x(i)))+(4*(f(x(i+1))))+f(x(i+2));
end
summa= f(x(1))+2*sum(f(x(3:2:end-2)))+4*sum(f(x(2:2:end)))+f(x(end));
The function we are supposed to use is the simple cos(x) and then compare it to sin(1)
So basically, the upper function gives me wrong on the second decimal while the lower is correct all the way to the 12th decimal. I would assume this is because it rounds differently but why and where? Is it when the sum is added to the next iterration or does it have to o something with the for loop that the first function has to use?
thank you

Answers (1)

Jan
Jan on 19 Dec 2011
This is no rounding effect, but the formulas are different. Simply write down the loop and the vectorized version explicitely for n=4 to find the difference.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!