是否有可能计算有限级数的值,比如,
使用 LaTeX 3?
答案1
是的,你可以,而且相当容易。
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\computesum}{mmm}
{% pass control to an internal function
\svend_compute_sum:nnn { #1 } { #2 } { #3 }
}
% a variable for storing the partial sums
\fp_new:N \l_svend_partial_sum_fp
\cs_new_protected:Npn \svend_compute_sum:nnn #1 #2 #3
{
% clear the variable
\fp_zero:N \l_svend_partial_sum_fp
% for k from #1 to #2 ...
\int_step_inline:nnnn { #1 } { 1 } { #2 }
{
% ... add the current value to the partial sum so far
\fp_add:Nn \l_svend_partial_sum_fp { #3 }
}
% deliver the value
\fp_use:N \l_svend_partial_sum_fp
}
\ExplSyntaxOff
\begin{document}
$\computesum{0}{0}{#1^2}$\par
$\computesum{0}{1}{#1^2}$\par
$\computesum{0}{2}{#1^2}$\par
$\computesum{0}{3}{#1^2}$\par
$\computesum{0}{4}{#1^2}$\par
$\computesum{0}{5}{#1^2}$\par
$\computesum{0}{6}{#1^2}$\par
$\computesum{0}{7}{#1^2}$\par
$\computesum{0}{8}{#1^2}$\par
\end{document}
请注意,第三个参数#1
代表求和索引。
在示例中,作为#1^2
传递给;由于参数在 内部使用,其中代表当前索引,因此奇迹发生了。#3
\svend_compute_sum:nnn
\int_step_inline:nnnn
#1
;-)
参数应为浮点表达式的合法代码。因此,除非您自己定义阶乘,否则无法计算阶乘。
如果您的加数始终是整数,则可以将全部更改fp
为int
。
如果你也加载siunitx
并将内部函数更改为
\cs_new_protected:Npn \svend_compute_sum:nnn #1 #2 #3
{
\fp_zero:N \l_svend_partial_sum_fp
\int_step_inline:nnnn { #1 } { 1 } { #2 }
{
\fp_add:Nn \l_svend_partial_sum_fp { #3 }
}
\num { \fp_use:N \l_svend_partial_sum_fp }
}
然后
$\computesum{0}{300}{#1^2}$
将打印类似
答案2
您可以加载xintexpr为此,并LaTeX3
休息一下。
\documentclass[12pt]{article}
\usepackage[hscale=0.75]{geometry}
\usepackage{xintexpr}
\usepackage{siunitx}
\usepackage{shortvrb}
\begin{document}
$$\sum_{i=1}^{300} i^2=\num{\xinttheexpr add(i^2, i=1..300)\relax }$$
% For some reason, this doesn't go through:
% \num{\xintthefloatexpr [14] add(1/i^2,i=1..50)\relax}
% one needs to first expand the \num argument:
% \expandafter\num\expandafter
% {\romannumeral-`0\xintthefloatexpr [14] add(1/i^2,i=1..50)\relax}
%
The float version does each addition with 16 digits floats, hence the last
digit may be a bit off.
$$\sum_{i=1}^{50} \frac1{i^2}=
\xintFrac{\xinttheexpr reduce(add(1/i^2,i=1..50))\relax}
\approx \xintthefloatexpr add(1/i^2,i=1..50)\relax$$
If one has anyhow computed an exact value, it is better to deduce the
float from it rather than evaluating the sum as a sum of floats.
\noindent\verb|\oodef\MySum {\xinttheexpr reduce(-add((-1)^i/i^2,i=1..50))\relax }|
\oodef\MySum {\xinttheexpr reduce(-add((-1)^i/i^2,i=1..50))\relax }
$$\sum_{i=1}^{50} \frac{(-1)^{i-1}}{i^2}=
\xintFrac{\MySum}$$
\verb|$$\xintDigits:=48; \approx\xintthefloatexpr \MySum\relax$$|
$$\xintDigits:=48; \approx\xintthefloatexpr \MySum\relax$$
\end{document}