ans =
Um, this is WRONG. Basic integral calculus does NOT say a result should never be negative. You are possibly misunderstanding what an integral means, as compared to the concept of area.
For example, what is the integral of the simple function y = -x, from 0 to 1? I'll use MATLAB here.
syms x
y(x) = -x;
PLOT IT FIRST. ALWAYS PLOT EVERYTHING.
fplot(y,[0,1])
xlabel X
ylabel Y
grid on
As you can see, y is negative over the entire region of interest.
int(y,0,1)
And in fact, the integral is -1/2. Yes. An integral CAN be negative, even though you may think of an integral as something representing area. It can be negative.
Let me ask a different question. What is the area between the x axis, and the function y, over the support for x of [0,1]? Now we would be using an integral to compute a POSITIVE area, because we are asking for an area between two lines. We might do it in a symbolic form:
ax(x) = sym(0);
int(ax - y,0,1)
Note that I've not needed to use abs at all there. If the curves actually cross, then I would need to think about absolute values to get the positive area.
The point here? IF you were asked to compute an area between things, then it makes sense that the result is positive. But if you are going to compute an integral, using a trapezoidal rule, then the sign is what it is. For example, what is the integral of the curve sin(x), for x between 0 and 2*pi?
fplot(sin(x),[0,2*pi])
yline(0)
int(sin(x),0,2*pi)
The two lobes cancel out, giving exactly zero. And trapezoidal rule would agree. I will just use trapz so I won't need to use (and validate) your code.
X = linspace(0,2*pi);
Y = sin(X);
trapz(X,Y)
Note tht trapz gives me some floating point crap, but it is still effectively zero.
BUT the area between the curve and the x axis is a different thing. That is known to be 4.
int(abs(0 - sin(x)),0,2*pi)
trapz(X,abs(0 - sin(X)))
And to within a reasonable tolerance, trapz agrees. (Note that for such a function, a trapezoidal rule will always under-estimate the area.)
The problem is, there is an ambiguity, something we cannot resolve, because we don't see the problem statement. Did the problem statement explicitly request you compute the integral using trapezoidal rule? Did the problem statement ask you to compute an area between things? Or, is the problem statement itself a bit ambiguous, poorly stated, so it asks you to compute an area "under" a curve that is both positive and negative? In the latter case, only your teacher could remove the ambiguity of a poorly phrased problem. I would hope the question was well posed, and you have merely misinterpreted it, but teachers are sometimes sloppy in what they ask.