Write a function to approximate the area under the curve of
Write a function to approximate the area under the curve of a function (e.g. approximate the integral). Your approximation must use the following algorithm.
The function should be named find_area_under_curve. The function will take the parameters a, b, f and N. Parameters a and b are scalar floating point values that represent the begin and the end of the interval over which we will be calculating the area under the curve. And N represents a scalar integer value, which represents the number of rectangles we will divide the interval up into to compute the approximation. f will be another python (vectorized) function of a single variable (or array of variables) f(x), that returns the value of the function at the given location(s) x.
Your approximation should work by dividing the interval up into N rectangles. For each rectangle, compute the midpoint of the slice and calculate the height of the rectangle at this midpoint of the slice. Then calculate the answer by summing up all of your computed rectangular slices, and returning this sum as the approximate area under the curve. An example of calling your function, and the correct answer, is shown here:
| Write a function to approximate the area under the curve of a function (e.g. approximate the integral). Your approximation must use the following algorithm. The function should be named Your approximation should work by dividing the interval up into N rectangles. For each rectangle, compute the midpoint of the slice and calculate the height of the rectangle at this midpoint of the slice. Then calculate the answer by summing up all of your computed rectangular slices, and returning this sum as the approximate area under the curve. An example of calling your function, and the correct answer, is shown here: |
Solution
def f(x):
return 0.25*x**3 - 2.5*x**2 + 5*x +8
def find_area_under_curve(a,b,f,n):
\"\"\"
Approximate the area under fn in the interval [a,b]
by adding the area of n rectangular slices.
\"\"\"
a = float(a)
b = float(b)
area = 0.0
for slice in range(n):
left = a + (b-a)*slice/n
right = a + (b-a)*(slice+1)/n
mid = (left + right)*0.5
height = f(mid)
width = right - left
area += height * width
return area
print \"Area is: \", find_area_under_curve(0, 8.0,f, 10)
Output:
Area is: 53.12
