Поэтому я написал команду в качестве домашнего задания, чтобы правильно отображать комплексные числа. Например, когда я пишу, \complfull{5}{-2}
вывод получается 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}
Этот код выдает мне сообщение об ошибке для входных данных типа $\complfull{\dfrac{-1}{12}}{-3}$
Вот сообщения об ошибках:
Undefined control sequence. $\complfull{\dfrac{-1}{12}}{-3}
TeX capacity exceeded, sorry [input stack size=10000]. $\complfull{\dfrac{-1}{12}}{-3}
Однако когда я делаю что-то подобное, все $\displaystyle\complfull{\frac{1}{2}}{-1}$
работает просто отлично.
В чем причина проблемы?
решение1
Переход на другой метод тестирования и очистка кода (не вижу смысла использовать \textit{i}
здесь , так как i
он и так выделен курсивом в математическом режиме.
Я уверен, что это можно сделать еще проще. Версия now больше не использует ничего из, xstring
так как их тесты довольно хрупкие.
Использование \NewDocumentCommand{\complfull}{m >{\TrimSpaces} m}{
make sure that #2
никогда не начинается с пробела, так как это нарушит проверку того, начинается ли мнимая часть с -
.
\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}
решение2
(Я переписал ответ, чтобы решить проблему форматирования ОП и сделать его более общим.)
Вот ответ на основе LuaLaTeX. Он не делает никаких предположений осодержаниедействительной и мнимой частей комплексного числа, за исключением того, что мнимая часть может начинаться с символа -
. (Напротив, начальный +
символ не допускается; однако это ограничение может быть ослаблено при необходимости.)
Макрос \complfull
можно использовать как в текстовом, так и в математическом режиме. \complfull{\dfrac{-1}{12}}{-3}
Это не вызывает никаких проблем — при условии, что загружен amsmath
пакет, предоставляющий макрос .\dfrac
% !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}
решение3
Ответ на ваш вопрос: $\complfull{\dfrac{-1}{12}}{-3}$
генерирует ошибку, потому что ваш \complull
макрос применяет \IfStrEq
свои аргументы и \IfStrEq
расширяет их во время обработки \edef
. И \dfrac
макрос не определен как \protected\def
. Он использует старый и малоизвестный \protect
метод LaTeX, который не работает с \edef
.
Проблема, которую вы решаете, интересна. Я показываю, что мы можем сделать с 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
Макрос \complfull
полностью расширяем и не расширяет свои аргументы при обработке макросов \isequal
.\qcasesof