why does 'sum' and 'trapz' function show same result ?

20 次查看(过去 30 天)
Just found the same result for "sum" and "trapz" function. is it same for uniform spacing (i think here is1) in trapz ?
if yes, then can use 'sum' function for integration instead of 'trapz', right ?
if no, what can be the possible reason ?
attached the 'mat' file here.
Code:
clear;
A=load('positive_value.mat');
power_positive_value=A.B;
integration=trapz(power_positive_value)
summation=sum(power_positive_value)
Result:
integration =
5.9126e+06
summation =
5.9126e+06

采纳的回答

John D'Errico
John D'Errico 2021-12-14
Um, no. Sum is not the same as trapz. Are they close, under some circumstances? Well, yes.
format long g
sum(B)
ans =
5912588.32712044
trapz(B)
ans =
5912588.3236019
Do you see they are not the same result?
Is sum close? Yes. And that is because when you use sum and trapz, trapz first assumes a unit stride between the points. If the stride was not 1, then trapz would not produce something even close. This gets into the question of what an integral is, and what rectangle rule means, etc. I won't teach a beginning calc course here. Sorry. But if we assume a stride of 1, then you still see they are not identical.
Anyway, as you can see, sum is NOT the same. If you look closely at the formula for rectangle rule to approximate an integral, and then look at the formula for trapz, you will see they essentially only differ at the ends. And since your vector B is almost zero at each end, then sum and trapz will be quite close in their prediction.
  2 个评论
Walter Roberson
Walter Roberson 2021-12-14
Right, in the case with regular stride and where the endpoints happen to be zero, the trapz and sum happen to have the same result.

请先登录,再进行评论。

更多回答(1 个)

the cyclist
the cyclist 2021-12-14
sum() and trapz() do not give the same result, even assuming uniform spacing:
Y = [1 2 3 4 5];
sum(Y)
ans = 15
trapz(Y)
ans = 12
It only seemed to be the same in your case, because of the large numbers involved, but sum(B) and trapz(B) do not give the same value in your case, either. Try subtracting those two values, to see the relatively small difference.

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by