[Tex/LaTex] problem in numbering equations using \numberwithin{equation}{subsection}

numbering

I'm writing an article where the first two sections have no subsection, but third one has two subsections. 1st section has 2 equations, 2nd has 3 equations and third one has 2+2 equations.

When I use \numberwithin{equation}{subsection}, I get the following numbering for the equations:

1st section

1.0.1

1.0.2

2nd section

2.0.3

2.0.4

2.0.5

3rd section

1st subsection

3.1.1

3.1.2

2nd subsection

3.2.1

3.2.2

But is there any way to get the equation number of 2nd section as

2nd section

2.0.1

2.0.2

2.0.3

?

Best Answer

Here are two ways of doing things, with the help of the changcntr package. First, if you do not want to display 0for non-existent subsections — i.e. if there is no subsection at one point, display only the section number+the equation number:

\documentclass[11pt,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{chngcntr}
\usepackage{etoolbox}
\counterwithin*{equation}{section}
\counterwithin*{equation}{subsection}
\renewcommand\theequation{\ifnumgreater{\value{subsection}}{0}{\thesubsection.}{\thesection.}\arabic{equation}}%

\begin{document}

\section{A First Section}
\begin{equation}
a = b
\end{equation}
\begin{equation}
a + c = b + c
\end{equation}
\begin{equation}
a × c = b × c
\end{equation}

\section{A Second Section}
\begin{equation}
a = b
\end{equation}
\begin{equation}
a + c = b + c
\end{equation}

\section{A Third Section}

An extra equation :
\begin{equation}\
  \ln a = \ln b
\end{equation}
\subsection{First subsection}
\begin{equation}
a = b
\end{equation}
\begin{equation}
a + c = b + c
\end{equation}

\subsection{Second subsection}
\begin{equation}
a = b
\end{equation}
\begin{equation}
a + c = b + c
\end{equation}

\end{document} 

enter image description here

If you want the 0 to be displayed, remove from the preamble \renewcommand\theequation{…} and \usepackage{etoolbox}, and replace counterwithin*{equation}{subsection} with the non-starred version.

enter image description here