I am completely new to Mathematica. Basically I was trying to write a code to plot a function and draw the approximate area by rectangles. To be more precise, plot a function f
on an interval $[a,b]$, choose a step size $n$, divide the interval in n
parts (so let's say $h=(b-a)/n$) and then draw the rectangles with coordinates $(a+ih,f(a+ih)),(a+(i+1)h, f(a+(i+1)h))$. I don't know how to store the information relative to the several rectangles. I would like to define a list
or array
(not sure how to call it) of rectangles parametrized by $i$, so something like:
For[i = 0, i < n,
R[i] = Rectangle[{a + i h, f[a + i h]}, {a + (i + 1) h, f[a + (i + 1) h]}]]
which clearly doesn't work. I can't seem to find an appropriate way to do this.
I am attaching the code I wrote for a single rectangle, so if you also have any suggestion on how to improve that, it would be greatly appreciated. thank you!
f[x_] := x^2
a = 0
b = 2
n = 3
h = (b - a)/n
R = Rectangle[{a , f[a ]}, {a + h, f[a + h]}]]
r = Graphics[{ Opacity[0.2], Blue, R}]
Show[Plot[f[x], {x, a, b}], r ]
I would like to thank everyone for all of your answers!
Epilog
to display your rectangle along with your plot. For more than one rectangle, there'sTable[]
. Alternatively, useGraphics[r]
instead of justr
in your last line. $\endgroup$