Write a polynomial fraction from its either partial fraction or coefficients of numerator and denominator

math-modepgffor

I need to robustly generate the displayed equation from either

1- the coefficients of numerator and denominator defined by \NumCoeffMat and \DenCoeffMat, respectively

2- or the partial fraction terms defined by \PartialFraction

enter image description here

P.S. The coefficient of the highest order in the denominator is always positive one, so it is not given in the arrays.

Any coefficient of zero should exclude its associated order of s from the written expression.

\documentclass{article}

\edef\NumCoeffMat{{4, 32, 62}} % numerator coefficients (i.e. numerator =  4s^2 + 32s + 62)
\edef\DenCoeffMat{{12, 47, 60}} % denominator coefficients (i.e. denominator = s^3 + 12s^2 + 47s + 60)

\def\PartialFraction{1/-3, 2/-4, 1/-5} % gain/coefficient and root (i.e. 1/(s+3) + 2/(s+4) + 1/(s+5) )

\begin{document}
    \[
    \frac{4\,s^2 + 32\,s + 62}{s^3 + 12\,s^2 + 47\,s + 60}
    \]
\end{document}

Best Answer

Here is a general macro to write polynomials. The first argument is the indeterminate and the second is the list of coefficients

\documentclass{article}

\usepackage{pgffor}

\newcount\degree
\newif\ifzero
\newif\ifcoeff

% \polynomial{<indeterminate>}{<list of coefficients>}
\newcommand*\polynomial[2]{%
  \global\degree=0\relax
  \foreach\x in {#2} {\global\advance\degree 1\relax}%
  \ifnum\degree=0
    0%
  \else
    \global\zerotrue
    \foreach\coeff in {#2} {%
      \global\advance\degree-1
      \coefffalse
      \ifnum\coeff=0 \else
        \ifnum\coeff>0 \ifzero\else+\fi\fi
        \ifnum\coeff=-1
          -\ifnum\degree=0 1\fi
        \else\ifnum\coeff=1
          \ifnum\degree=0 1\fi
        \else
          \coefftrue  
          \coeff
        \fi\fi 
        \ifnum\degree>0\relax\ifcoeff\,\fi{#1}\ifnum\degree>1^{\the\degree}\fi\fi
        \global\zerofalse
      \fi
    }%
    \ifzero 0\fi
  \fi
}

\newcommand\PartialFraction[2][s]{%
  \global\zerotrue
  \foreach \n/\r in {#2} {%
    \ifnum\n=0 \else
      \ifnum\n<0
        -\edef\n{\the\numexpr-\n\relax}%
      \else
        \ifzero\else +\fi
      \fi
      \global\zerofalse
      \frac{\n}{s\ifnum\r>0 -\r\else\ifnum\r<0 +\the\numexpr-\r\relax\fi\fi}%
    \fi}%
  \ifzero 0\fi
}

\begin{document}
\[
    \frac{\polynomial{s}{4,32,62}}{\polynomial{s}{1,12,47,60}}
\]
\[
    \PartialFraction{1/-3, 2/-4, 1/-5}
\]
\end{document}

The next macro allows you to give the coefficients the way you want

% \Fraction[<indeterminate> defaults to s]
\newcommand\Fraction[1][s]{%
  \begingroup
    \def\polyaux##1{{1,##1}}%
    \edef\next{\noexpand\frac{\unexpanded{\polynomial{#1}}\NumCoeffMat}{\unexpanded{\polynomial{#1}}\expandafter\polyaux\DenCoeffMat}}%
    \next
  \endgroup
}
\[
  \def\NumCoeffMat{{4, 32, 62}}  % numerator = 4s^2+32s+62 
  \def\DenCoeffMat{{12, 47, 60}} % denominator = s^3+12s^2+47s+60
  \Fraction
\]
Related Question