8

in this picture: there are 6 intersection points. I need 6 auto change when number of intersection points change. Can you help me? enter image description here

my code:

\documentclass[tikz,border=5mm]{standalone}

\usepackage[utf8]{vietnam}

\usetikzlibrary{intersections}

\begin{document}

\begin{tikzpicture}[smooth]

\draw[gray!30](-3,-3) grid (3,3);

\draw[->](-3,0)--(3,0) node[below]{$x$};

\draw[->](0,-3)--(0,3) node[right]{$y$};

\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{(\x)^3-3*(\x)}) 
node[right, red] {$y=x^3-3x$};

\draw[red,name path=tron] (0,0) circle(2);

\fill[violet,name intersections={of=hamso and tron,name=A,total=\t}]

\foreach \i in {1,...,\t} {(A-\i) circle (2pt) node[above]{\i}};
\path (current bounding box.south) node[below]{There are: \fbox{6} intersection points};
\end{tikzpicture}

\end{document}

1 Answers1

8

I believe Henri wanted to tell you that you only make \t global (or smuggle it out of the path). One way of accomplishing this is to add \pgfextra{\xdef\myt{\t}} to the path, which stores \t in the global macro \myt. (Advanced possibilities of smuggling can be found e.g. here, but I think here you almost necessarily need to globalize the macro.) EDIT: Made this handle the case of 0 intersections, too.

\documentclass[tikz,border=5mm]{standalone}

\usepackage[utf8]{vietnam}

\usetikzlibrary{intersections}

\begin{document}

\begin{tikzpicture}[smooth]

\draw[gray!30](-3,-3) grid (3,3);

\draw[->](-3,0)--(3,0) node[below]{$x$};

\draw[->](0,-3)--(0,3) node[right]{$y$};

\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{(\x)^3-3*(\x)}) 
node[right, red] {$y=x^3-3x$};

\draw[red,name path=tron] (0,0) circle(2);

\fill[violet,name intersections={of=hamso and tron,name=A,total=\t}]
\ifnum\t>0
foreach \i in {1,...,\t} {(A-\i) circle (2pt) node[above]{\i}}
\fi
\pgfextra{\xdef\myt{\t}};
\path (current bounding box.south) node[below]{There are: \fbox{\myt} intersection points};
\end{tikzpicture}

\end{document}

enter image description here

If you change the cubic curve to

\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{7+(\x)^3-3*(\x)}) 
node[right, red] {$y=7+x^3-3x$};

you'll get

enter image description here

  • page 145 of the manual states -- /tikz/intersection/total=(macro) This key means that the total number of intersections found will be stored in macro --- could you please tell how to print the output of this macro – js bibra Feb 21 '20 at 06:19
  • 1
    @jsbibra Yes, this is what the macro says, but the macro is a local macro, i.e. it is only "known" inside the path. You can print it out by adding \pgfextra{\typeout{I found \t\space intersections}}; to the path. But this literally prints it it out. –  Feb 21 '20 at 06:27
  • thank you so much. @Schrödinger'scat You can tell me when they do not have intersection, how to handle errors? – Jack Nguyễn Feb 21 '20 at 06:36
  • 1
    @JackNguyễn Good point! Added. –  Feb 21 '20 at 06:42