[Tex/LaTex] \numberwithin{equation}{subsection} fails for subsections “0”

equationsnumbering

\numberwithin{equation}{subsection} is in the preamble of an article.
Equations in sections before subsection 1 of that section begin numbering as x.0.y+1, where "y" is the number of the last equation of the last subsection of the previous section. (Numbers are OK in subsections, as 2.1.1, etc.) I can't see how such behavior would ever be desirable. Example:

\documentclass[12pt]{article}
\usepackage{amsmath}
\numberwithin{equation}{subsection}
\begin{document}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\end{document}

produces equations numbered (1.0.1), (1.1.1), (1.2.1), (1.2.2), (2.0.3), (2.1.1), (3.0.2), (3.1.1).

Best Answer

Update

Since the release of LaTeX from 2018/04/01 the mentioned package chngcntr is now part of the LaTeX kernel -- it's not necessary to load it separately.

Using \numberwithin{equation}{subsection} changes the counter output format and shifts the resetting of the equation counter from section to subsection level (i.e. each time \stepcounter{subsection} is used. However, this means that an orphane equation after a \section, but before \subsection will just use the old counter value, from a previous equation.

This resets the counter of equation number each time a new \section is used, but will not change the \theequation command (being the counter formatting macro)

\makeatletter
\@addtoreset{equation}{section}
\makeatother

As an alternative to this low-level variant, it's possible to use

\usepackage{chngcntr}
\counterwithin{equation}{section}

in the preamble.

However, this will not solve the issue with trailing 0 if the subsection number is 0. This can be attacked with a conditional within \theequation or -- the better way -- avoid equations outside of \subsection if subsection is the driver counter.

\documentclass[12pt]{article}
\usepackage{amsmath}
\makeatletter
\@addtoreset{equation}{section}
\makeatother
\numberwithin{equation}{subsection}

\begin{document}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\end{document}

enter image description here