I want to give a lecture note to my students explaining the trapezoidal rule. Can anyone help how to draw these shapes together using latex.
-
1Welcome to TeX.SX! Questions about how to draw specific graphics that just post an image of the desired result are really not reasonable questions to ask on the site. Please post a minimal compilable document showing that you've tried to produce the image and then people will be happy to help you with any specific problems you may have. See minimal working example (MWE) for what needs to go into such a document. – Stefan Pinnow Jun 05 '22 at 15:38
1 Answers
This is a solution with a macro for the axis and the function that also creates nodes which help to draw the rectangles or trapeziums:
The code:
\documentclass[tikz,border=2mm]{standalone}
\tikzset{declare function={f(\x)=0.25(\x-2.5)^3-0.75\x+5);}}
\newcommand{\myfunction}[2]
{
\begin{scope}[shift={(#1,0)}]
\draw[-latex] (-0.5,0) -- (5,0) node[below] {$x$};
\draw[-latex] (0,-0.5) -- (0,5) node[left] {$y$};
\draw[thick,cyan] plot[domain=0.5:4.5,samples=41] (\x,{f(\x)});
\node at (3.25,3.5) {$y=f(x)$};
\foreach\i in {0,1,2,3,...,8}
{
\pgfmathsetmacro\j{0.5*\i+0.5}
\coordinate (x\i) at (\j,0);
\coordinate (y\i) at (\j,{f(\j)});
}
\foreach\i in {0,1,2}
\node[below] at (x\i) {$x_\i$};
\node[below] at (x7) {$x_{n-1}$};
\node[below] at (x8) {$x_n$};
\node[yshift=-0.75cm] at (x0) {\strut$a$};
\node[yshift=-0.75cm] at (x8) {\strut$b$};
\node[yshift=-1cm] at (x4) {(#2)};
\end{scope}
}
\begin{document}
\begin{tikzpicture}[line join=round,line cap=round,scale=1.25]
% left
\myfunction{0}{A}
\foreach\i in {0,1,2,3,7}
{
\pgfmathtruncatemacro\j{\i+1}
\draw[gray] (x\j) rectangle (y\i);
\fill (y\i) circle (1pt);
}
% center
\myfunction{6}{B}
\foreach\i in {0,1,2,3,7}
{
\pgfmathtruncatemacro\j{\i+1}
\draw[gray] (x\i) rectangle (y\j);
\fill (y\j) circle (1pt);
}
% right
\myfunction{12}{C}
\foreach\i in {0,1,2,3,7,8}
{
\pgfmathtruncatemacro\j{\i+1}
\ifnum\i<8
\draw[gray] (x\i) -- (y\i) -- (y\j) -- (x\j);
\fi
\fill (y\i) circle (1pt);
}
\end{tikzpicture}
\end{document}
- 28,426

