是否可以計算有限級數的值,例如,
使用 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
您可以載入新泰普為此,請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}