This question is related to Graphically approximating the area under a curve as a sum of rectangular regions.
I now was trying to adapt the code by MarcoB to get the approximation of the integral by trapezoids, and I used the function Line
. I only need to color the trapezoids now. Is it possible to adapt the following code to do that? Thank you
f[x_] = Sin[x]
Manipulate[
lines = Table[ {Blue,
Line[{{a + i (b - a)/n,
f[a + i (b - a)/n]}, {a + (i + 1) (b - a)/n,
f[a + (i + 1) (b - a)/n]}}] }, {i, 0, n - 1, 1}];
Show[{Plot[f[x], {x, a, b}, PlotStyle -> {Red, Thick},
AxesOrigin -> {0, 0}], Graphics[{Thick, lines}]},
ImageSize -> Large],
{{a, 0}, -10, 10},
{{b, 6}, -10, 10},
{{n, 15} , 1, 40, 1}
]
Answer
Well, I could hardly be expected to resist...
Rather than using Line
objects, it would seem more natural to use Polygon
objects (see documentation). In the spirit of my suggestion to your previous question, I am leaving the simple rectangle approximation in the code as well, as an option to the Manipulate
:
f[x_] := Sin[x]
Manipulate[
polygons = {
Table[{Opacity[0.05], EdgeForm[Gray],
Rectangle[
{a + i (b - a)/n, 0},
{a + (i + 1) (b - a)/n, f[a + i (b - a)/n]}
]},
{i, 0, n - 1, 1}
],
Table[{Opacity[0.05], EdgeForm[Gray],
Polygon[{
{a + i (b - a)/n, 0},
{a + i (b - a)/n, f[a + i (b - a)/n]},
{a + (i + 1) (b - a)/n, f[a + (i + 1) (b - a)/n]},
{a + (i + 1) (b - a)/n, 0}
}]
},
{i, 0, n - 1, 1}]
};
Show[{
Plot[f[x], {x, a, b}, PlotStyle -> {Red, Thick}, AxesOrigin -> {0, 0}],
Graphics[ polygons[[type]] ]
},
ImageSize -> Large
],
{{a, -1}, -10, 10},
{{b, 6}, -10, 10},
{{n, 5}, 1, 40, 1},
{{type, 2, "polygon\ntype"}, {1 -> "left rectangles", 2 -> "trapezoids"}}
]
Comments
Post a Comment