Hi, for my class I have to code a program which will find the integral of x^2 + 2 from 0 to 2 using the rectangle method for multiple rectangles n. I have to output n in one column and the corresponding integral in the other in a text file. In the code below I have loaded in my values of n from the n.txt file. This file is just a column containing 1 and 2. Therefore h will have 2 values. I then compute the area by letting the right hand side of the rectangle lie on the curve.
When n=1, I get the correct answer which is f(2)*h = 6*2 = 12. However, for n=2, I get an answer of 15 which shouldn't be the case if we consider two uniform rectangles: f(1)*h + f(2)*h with h=(2-0)/2 = 1. Therefore for 2 rectangles, the result should be (3*1)+(6*1)=9. I'm not sure how to correct my code. Could someone see what I'm doing wrong?
So n should be the number of rectangles you use to compute the integral right? The sum of the area of the rectangles would be the integral. Larger n means a more accurate answer.
Now how do you compute the area of a rectangle? You need to multiply its width and length, or base and height, whatever you want to call it. In this case, we know that the integral is from 0 to 2, represented by n rectangles. So width (or base) of each rectangle is 2.0 / n.
The length (or height) is computed from the calculation x^2 + 2. The x in this case would be i * width for the i-th rectangle. So to calculate the integral, you would need to compute the sum of width * (pow(i * width, 2) + 2) for n rectangles with i representing the current rectangle.
NOTE: I am assuming that the upper right corner of the rectangle touches the curve.
EDIT: Looking at your code, you actually have most of it right. You just need to fix line 35.
Thanks for the reply. I'm not sure what I have to do to line 35. Wouldn't f(a+i*h) cover it because a=0? And you're right, having more rectangles should give me a more accurate answer, but my code computes the calculation incorrectly and I'm not sure why.
You showed that you could do file input/output in the code in your first post. Did someone else write that for you? If so, well then you need to at least do some work of your own.