7
$\begingroup$

I am reading an article about Euler summation formula.

Let $n$ be a positive integer which is greater than or equal to $2$.
Let $f$ be a function from $[1,n]$ to $\mathbb{R}$.
Let $g$ be a function from $[1,n]$ to $\mathbb{R}$ such that $g(x)=f(k)$ if $x\in[k,k+1)$ for some $k\in\{1,2,\dots,n\}$.
Let $S:=\{x\in [1,n]\mid f(x)\leq g(x)\}.$
Let $T:=\{x\in [1,n]\mid g(x)< f(x)\}.$
Let $B:=\{(x,y)\in\mathbb{R}^2\mid x\in S, f(x)\leq y\leq g(x)\}.$
Let $R:=\{(x,y)\in\mathbb{R}^2\mid x\in T, g(x)\leq y\leq f(x)\}.$
I want to paint the area $B$ blue.
I want to paint the area $R$ red.

I copied the following code:

n = 10;
f[x_] := Sin[x];
rectangles[f_, a_, b_, n_] := {
    Opacity[0.0],
    Blue,
    EdgeForm[Black],
    N@Table[Rectangle[{a + k (b - a)/n, 0}, {a + (k + 1) (b - a)/n, f[a + k (b - a)/n]}], {k, 0, n - 1}]
};
Plot[f[x], {x, 1, n}, Epilog -> rectangles[f, 1, n, n-1],
   AxesOrigin -> {1, 0}, ImageSize -> Large, Frame -> True]

enter image description here

I want an image like the following image:
enter image description here

Thank you very much.

$\endgroup$
2
  • 1
    $\begingroup$ This should be achievable by describing the areas covered by rectangles as a function and using the Filling option between the two functions. $\endgroup$
    – kirma
    Aug 14 at 3:57
  • $\begingroup$ @kirma Thank you very much for your answer. $\endgroup$
    – tchappy ha
    Aug 14 at 3:58

1 Answer 1

9
$\begingroup$

A quick hack:

n = 10;
f[x_] := Sin[x];
rectangles[f_, a_, b_, n_] := {Opacity[0.0], Blue, EdgeForm[Black], 
   N@Table[Rectangle[{a + k (b - a)/n, 0}, {a + (k + 1) (b - a)/n, 
       f[a + k (b - a)/n]}], {k, 0, n - 1}]};
Plot[{f[x], f[Floor[x]]}, {x, 1, n},
 PlotStyle -> {Automatic, None}, Filling -> {1 -> {{2}, {Blue, Red}}}, 
 Epilog -> rectangles[f, 1, n, n - 1], AxesOrigin -> {1, 0}, 
 ImageSize -> Large, Frame -> True]

enter image description here

The stepped function is achieved just by Floor, two-sided filling between the normal and stepped function is achieved with Filling option and just for completeness, plot style for the stepped function is set to None.

$\endgroup$
1
  • $\begingroup$ kirma, Thank you very very much for your excellent answer. $\endgroup$
    – tchappy ha
    Aug 14 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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