TransWikia.com

How to draw this function graph with plot operation(TIKZ,Loop)

TeX - LaTeX Asked by hebtuzrl on December 10, 2020

I wish to draw a function graph,
The analytical formula of the function is:
enter image description here

I can use the following code to draw an image of a specific function

But I want to be concise, how to define a letter n,

Draw the corresponding function image with the change of n

I think it should be realized by loop, but I don’t know how to do it

What needs to be done?

documentclass{book}
usepackage{tikz}

begin{document}

begin{tikzpicture}     
    draw[->,>=stealth] (-4,0)  --  (4,0)   node[below] {$ x  $};   
    draw[->,>=stealth] (0,-0.5)    --  (0,4)   node[right] {$ y  $};
    fill (0,0)  circle  (  0  )   node[  below   left  ] {  $  O  $  } ;

    draw[  domain=  -3  :  3  ,samples=  300  ] plot (  x,  {  
        abs(x) 
    });

    draw[  domain=  -3  :  3  ,samples=  300  ] plot (  x,  {  
        abs(x) + abs((x) +  1)  
    });

    draw[  domain=  -3  :  3  ,samples=  300  ] plot (  x,  {     
    abs(x) + abs((x) +  1)  + abs((x) +  2)  
    });
    
end{tikzpicture}

end{document}

One Answer

Use math library.

documentclass[tikz, border=1cm]{standalone}
usetikzlibrary{math}

begin{document}
begin{tikzpicture}
pgfset{fpu=true, fpu/output format=fixed}
tikzmath{
  function f(x, n) {
    real s;
    s = 0;
    for i in {0,...,n}{
      s = s + abs(x + i);
    };
    return s;
  };
}
pgfset{fpu=false}
draw[->,>=stealth] (-4,0) -- (4,0) node[below] {$x$};
draw[->,>=stealth] (0,-0.5) -- (0,15) node[right] {$y$};
fill (0,0) circle (2pt) node[below left] {$o$};
foreach i in {1,...,4} {
  draw [domain=-3:1, samples=300] plot (x, {f(x, i)});
}
end{tikzpicture}
end{document}

enter image description here

Answered by ZhiyuanLck on December 10, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP