1

I am trying to plot a function using tikz. Unfortunately I cannot use pgfplot because when I open the pgfplot package it collides with already existing latex drawing and plot codes used with tikz. Here is the code,

 \begin{tikzpicture}
 \draw[->] (-3,0) -- (4.2,0) node[right] {$x$};
 \draw[->] (0,-3) -- (0,4.2) node[above] {$y$};
 \draw[scale=0.7,domain=-3:3,smooth,variable=\x,blue] plot ({\x},  {1/(1+exp((-\x)/0.6))});
 \end{tikzpicture}

When I want to sharpen the step of the curve, I just decrease the number 0.6 to 0.2 or whatever. However, when I set this function with 0.2, I am getting error message that dimension too large. Is it possible to fix it with tikz?

Aschoolar
  • 147

2 Answers2

6

enter image description here

\documentclass{article}
\usepackage{tikz}
\begin{document}
You wish to plot 
\[f(x)~=~\frac{1}{1+\exp(-x/\alpha)}~=~\frac{1}{1+\exp(-2a\,x)}\]
with $a=1/(2\alpha)$. However,
\[f(x)~=~\frac{\exp(a\,x)}{\exp(a\,x)+\exp(-a\,x)}
~=~\frac{1}{2}\,\frac{\cosh(a\,x)+\sinh(a\,x)}{\cosh(a\,x)}
~=~\frac{1}{2}\,\left[1+\tanh(a\,x)\right]\;.\]
\begin{tikzpicture}
 \draw[->] (-3,0) -- (4.2,0) node[right] {$x$};
 \draw[->] (0,-3) -- (0,4.2) node[above] {$y$};
 \draw[scale=0.7,domain=-3:3,smooth,variable=\x,blue] plot ({\x}, 
 {exp(2.5*\x)/(exp(2.5*\x)+exp(-2.5*\x))});
\end{tikzpicture}
\begin{tikzpicture}
 \draw[->] (-3,0) -- (4.2,0) node[right] {$x$};
 \draw[->] (0,-3) -- (0,4.2) node[above] {$y$};
 \draw[scale=0.7,domain=-3:3,smooth,variable=\x,red] plot ({\x}, 
 {0.5*(1+tanh(2.5*\x))});
 \end{tikzpicture}
\end{document} 
  • It is a great alternative solution. However the issue with dimension too large is still there, for example, when 'a' is greater than 5. – Aschoolar Dec 31 '17 at 15:55
  • 1
    @Aschoolar Yes. But in most cases this happens when pgfplots encounters very large or small numbers. In your case, tanh is very very close to either 0 or 1 in the outer regions of the plot interval. You could equally well draws horizontal lines there, and this would solve the problem. –  Dec 31 '17 at 15:59
0

I found a fix for my problem from the previous question that's been posted. I adapted it to my problem, re-scaled the axis to see plot better, increased the sampling rate to make plot more smooth, and added extra code according to their solution. Here is the code.

\documentclass{article}
\usepackage{tikz}
\usepackage{expl3}
\ExplSyntaxOn
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\begin{document}
\begin{tikzpicture}
\draw[->] (-3,0) -- (3.5,0) node[right] {$x$};
\draw[->] (0,-0.5) -- (0,2) node[above] {$y$};
\draw[samples=400,scale=1,domain=-3:3,smooth,variable=\x,blue] plot ({\x}, {\fpeval{1/(1+exp((-\x+1)/0.01))}});
\end{tikzpicture}
\end{document} 

Here is the result for $\alpha=0.6$,

for $\alpha=0.6$

Here is the result for $\alpha=0.01$,

$\alpha=0.01$

Aschoolar
  • 147