Hice un comando de número complejo

Hice un comando de número complejo

Así que escribí un comando como tarea para representar números complejos correctamente. Por ejemplo, cuando escribo \complfull{5}{-2}la salida es 5-2i

\documentclass{scrartcl}

\usepackage{amsmath}
\usepackage{xstring}    %this package is needed for the if else commands like \IfStrEq

\newcommand{\complfull}[2]{     %This bracket covers the case for when the real part is zero
    \IfStrEq{#1}{0}{\IfStrEqCase{#2}{
        {0}         {0}                 %"If b is also zero, output zero"
        {1}         {i}     %"If b is just one, output 'i'(instead of '1i')"
        {-1}        {-i}}
    [#2\textit{i}]}{\IfStrEqCase{#2}{   %This bracket is the first command's "else" statement, so it covers the case when the real part is not zero
        {0}         {#1}                %"If the imaginary part is zero, output the real part"
        {1}         {#1+i}
        {-1}        {#1-i}}
    [\IfBeginWith{#2}{-}                %This covers the case when the imaginary part is negative and the real part is not zero. It is necessary because we can't have a number be displayed as "1+-4i", and doing it with brackets would necessitate every imaginary part to be written with brackets.
        {#1#2i}
        {#1+#2i}]}
}

\begin{document}
    
    \complfull{2}{-2}
    \complfull{0}{1}

\end{document}

Este código me da un mensaje de error para entradas como $\complfull{\dfrac{-1}{12}}{-3}$ Estos son los mensajes de error:

Undefined control sequence. $\complfull{\dfrac{-1}{12}}{-3}

TeX capacity exceeded, sorry [input stack size=10000]. $\complfull{\dfrac{-1}{12}}{-3}

Sin embargo, cuando hago algo así, $\displaystyle\complfull{\frac{1}{2}}{-1}$funciona bien.

¿Qué está causando el problema?

Respuesta1

Cambiar a un método de prueba diferente y limpiar el código (no veo ninguna razón para usarlo \textit{i}aquí, ya que iya está en cursiva en el modo matemático).

Estoy seguro de que esto se puede hacer aún más sencillo. La versión ahora ya no usa nada xstringporque sus pruebas son bastante frágiles.

El uso de \NewDocumentCommand{\complfull}{m >{\TrimSpaces} m}{asegúrese de que #2nunca comience con un espacio, ya que eso rompería la prueba para ver si la parte imaginaria comienza con -.

\documentclass[a4paper]{article}
\usepackage{amsmath}
\usepackage{etoolbox}

% this assumes the arg never starts with spaces
\def\ProcessFirstChar#1#2\END{%
  \def\FirstChar{#1}
}
\def\DASHCHAR{-}

% input a,b, need to generate z = a+bi in a nice way
\NewDocumentCommand{\complfull}{m >{\TrimSpaces} m}{
  % if a =0
  \ifstrequal{#1}{0}{
      \ifstrequal{#2}{0}{
          0
        }{
          \ifstrequal{#2}{1}{
              i
            }{
              \ifstrequal{#2}{-1}{
                  -i
                }{ 
                  #2i% default
                }
            }
        }
    }{
      % a is not zero
      #1% just leave a
      \ifstrequal{#2}{0}{%
          % Im(z) = 0, so nothing
        }{
          \ifstrequal{#2}{1}{
              + i
            }{
              \ifstrequal{#2}{-1}{
                  -i
                }{
                  % still need the case when b is negative, as we should not add a plus in this case
                  \expandafter\ProcessFirstChar#2\END
                  \ifx\FirstChar\DASHCHAR\else+\fi
                  #2i
                }
              }
            }
          }
        }

\begin{document}


$\complfull{0}{0}$

$\complfull{0}{1}$

$\complfull{0}{-1}$

$\complfull{0}{5}$

$\complfull{1}{0}$

$\complfull{1}{1}$

$\complfull{1}{-1}$

$\complfull{1}{5}$

$\complfull{1}{-5}$

$\complfull{0}{3}$

$\complfull{a}{ - b}$

$\complfull{0}{3}$

$\complfull{\frac{-1}{12}}{-3}$

$\complfull{\dfrac{-1}{12}}{-\dfrac12}$

$\complfull{\dfrac{-1}{12}}{\dfrac12}$

\end{document}

Respuesta2

(Reescribí la respuesta para resolver el problema de formato del OP con más generalidad).

Aquí hay una respuesta basada en LuaLaTeX. No hace suposiciones sobre lacontenidode las partes real e imaginaria del número complejo, excepto que la parte imaginaria puede comenzar con un -símbolo. (Por el contrario, +no se permite un símbolo inicial; sin embargo, esta restricción podría atenuarse si fuera necesario).

La \complfullmacro se puede utilizar tanto en modo texto como matemático. \complfull{\dfrac{-1}{12}}{-3}no plantea problemas, siempre y cuando el amsmathpaquete que proporciona la macro \dfracesté cargado.

ingrese la descripción de la imagen aquí

% !TEX TS-program = lualatex
\documentclass{scrartcl}
\usepackage{amsmath} % for '\ensuremath' macro
\usepackage{luacode} % for 'luacode' env. and '\luastringN' macro

\begin{luacode}
function complfull ( re , im ) -- inputs: real and imag. parts

  -- begin by stripping off any leading whitespace from 'im'
  im = im:gsub ( '^%s*' , '' ) 
  im = im:gsub ( '^%-%s*' , '-' )

  if im == '0' then -- real number
    return re 
  else 
    if re == '0' then -- imaginary number
      if im == '1' then 
        return 'i'
      elseif im == '-1' then 
        return '-i'
      else 
        return im..'i'
      end
    else -- complex number
      if im == '1' then 
        return re..'+i'
      elseif im == '-1' then 
        return re..'-i'
      else
        if im:sub(1,1)=='-' then 
          return re..im..'i'
        else 
          return re..'+'..im..'i'
        end
      end
    end
  end
end
\end{luacode}

\newcommand\complfull[2]{\ensuremath{\directlua{%
  tex.sprint(complfull(\luastringN{#1},\luastringN{#2}))}}}

\begin{document}
\complfull{1}{0}; 
\complfull{0}{1}, 
\complfull{0}{-1};  
\complfull{1}{1}, 
\complfull{1}{-1}; 
\complfull{\frac{1}{2}}{\frac{1}{2}},
\complfull{\frac{1}{2}}{-\frac{1}{2}};
\complfull{\dfrac{-1}{12}}{\exp(7)},
\complfull{\dfrac{-1}{12}}{-3}.
\end{document}

Respuesta3

La respuesta a su pregunta: $\complfull{\dfrac{-1}{12}}{-3}$genera un error porque su \complullmacro se aplica \IfStrEqa sus argumentos y \IfStrEqlos expande durante el procesamiento mediante \edef. Y la \dfracmacro no está definida como \protected\def. Utiliza un \protectmétodo LaTeX antiguo y oscuro que no funciona con \edef.

El problema que estás resolviendo es interesante. Muestro lo que podemos hacer con OpTeX:

\def\complfull#1#2{%
   \isequal{#1}{0}\iftrue \printimpart\empty{#2}%
                  \else {#1}\printimpart+{#2}%
                  \fi
}
\def\printimpart#1#2{%
   \qcasesof {#2}
   {}      {\ifx#1\empty 0\fi}
   {0}     {\ifx#1\empty 0\fi}
   {1}     {#1\imu}
   {-1}    {-\imu}
   \_finc  {\isminus #2\iftrue \else #1\fi {#2}\imu}%
}
\def\imu{{\rm i}}
\def\isminus #1#2\iftrue{\ifx-#1}

Test:
$\complfull{1}{0}; 
\complfull{0}{};
\complfull{0}{1}; 
\complfull{0}{-1};  
\complfull{1}{1}, 
\complfull{1}{-1}; 
\complfull{1\over2}{1\over2},
\complfull{1\over2}{-{1\over2}};
\complfull{-1\over12}{\exp(7)},$

\bye

La \complfullmacro es completamente expandible y no expande sus argumentos cuando se procesan macros \isequal.\qcasesof

información relacionada