I use the code below for drawing the Weierstrass function (from here). How can I change it to draw x²·weierstrass(x)?

\foreach \i in {1,...,19} {
    % \global makes these definitions last beyond the current iteration
    \global\edef\currentbn{2*\currentbn}    % b_n = 2 * b_n;
    \global\edef\weierstrass{\weierstrass + (1/(\currentbn)*cos((\currentbn*\x) r))}    % weierstrass = weierstrass + (1/b_n) cos(b_n*\x radians);
    \draw[thick, color=lightgray,step=0.25cm,solid] (-2,-0.75) grid (2,1.0);
    \draw[<->] (-2.1,0) -- (2.1,0) node[below right] {$x$};
    \draw[<->] (0,-0.9) -- (0,1.1) node[left] {$y$};
    \draw[color=blue, thick, domain=-2:2, samples=501, /pgf/fpu, /pgf/fpu/output format=fixed] 
        plot (\x, {\weierstrass});

Thanks in advance!


I just copied the definition from Jake's answer and multiplied the plot by x^2 to get

    \expandafter\c@pgfmath@counta\pgfmathresult pt\relax%
            \advance\c@pgfmath@counta by-1\relax%

\begin{axis}[axis lines=middle, axis equal image, enlarge y
\addplot [thick, black, samples=301, line join=round, domain=-2:2] 

enter image description here

  • 1
    Please avoid x^2 and use x*x instead. Even when it works, it takes much longer to compute. – John Kormylo Oct 1 '19 at 13:44
  • @JohnKormylo It is true that it makes it a bit faster when one uses x*x, but on my machine this is a ~3% effect for PDFLaTeX and ~5% for lualatex (which ironically takes longer here). – Schrödinger's cat Oct 1 '19 at 14:15
  • OTOH, it is just good applied math. Just as quadratic polynomials should be written as (a*x+b)*x+c. – John Kormylo Oct 1 '19 at 14:17
  • @Schrödinger'scat , thank's a lot!!! problem solved! – Kώστας Κούδας Oct 1 '19 at 18:13
  • @JohnKormylo , thank's for your advise! – Kώστας Κούδας Oct 1 '19 at 18: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.