2
$\begingroup$

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}
 ]
$\endgroup$

1 Answer 1

6
$\begingroup$

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"}}
]

Manipulate for trapezoid integral estimation

$\endgroup$
4
  • $\begingroup$ If one just wants the outlines of the polygons, it is a simple matter of inserting Directive[FaceForm[None], EdgeForm[Black]] in the appropriate spot. $\endgroup$ Commented May 7, 2015 at 10:09
  • $\begingroup$ Do we have a question about Lebesgue integrals coming up too? :-) $\endgroup$
    – LLlAMnYP
    Commented May 7, 2015 at 13:24
  • $\begingroup$ @LLlAMnYP I think I'd call myself out of that one though. I just barely understand the concept of Lebesgue integration, and that's on a good day! :-) $\endgroup$
    – MarcoB
    Commented May 7, 2015 at 20:25
  • $\begingroup$ Thank you! Before getting to Lebesgue there is approximation by Parabolas for Simpson's method! ahah $\endgroup$
    – Gio
    Commented May 8, 2015 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.