9

In many computer algebra systems, one can sum a sequence of numbers using the syntax sum(a(k), k, kStart, kEnd) for a sequence a(k) (of real and integer values) with the variable k.

What's the best and fastest way to do this with LaTeX?

For example, when you want to calculate thousands of values ​​for a table.

I've developed a MWE using foreach and fpeval.

enter image description here

\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\newcommand\Sum[4]{%
\def\mysum{0}%
\foreach #2 in {#3,...,#4}{% 
   \def\psum{\fpeval{(#1)}}%
   \xdef\mysum{\fpeval{\mysum+\psum}}%
}\mysum}

\begin{document}
Test 1: $\displaystyle\sum\limits_{k=1}^{100} k = \Sum{\k}{\k}{1}{100}$

\newcommand\binomial[2]{\fpeval{fact(#1)/(fact(#2)*fact(#1-#2))}}
Test 2: $\displaystyle\sum\limits_{k=0}^{5} \dbinom{5}{k}
= \Sum{  \binomial{5}{\k}  }{\k}{0}{5} =2^5 = \fpeval{2^5}$
\end{document}
10
  • 2
    lua. if lua is not an option, fastest for integer values is probably to use a plain loop with tex counts. o/w an expl3 loop with l3fp. Commented Jan 28 at 14:23
  • 1
    if it is integer arithmetic and within the size bounds of a tex integer use inteval not fpeval Commented Jan 28 at 14:27
  • and avoid foreach use one of latex's built in loops Commented Jan 28 at 14:28
  • @DavidCarlisle I can't promise that they are only integer values; think of the cumulative binomial distribution. Commented Jan 28 at 14:33
  • 1
    For adding large numbers of floating point values, process them in pairs, then process the pairs in pairs, etc. This is mostly used with statistical data. Commented Jan 28 at 15:22

5 Answers 5

12

it is easier to use lualatex and luacode. For example

\DocumentMetadata{}
\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage{luacode}
\begin{luacode}
function LuaSum(a,b,f)
  k = 0
  for i=a,b do
    k = k + f(i)
  end
  return k
end

function Binomial( n, k )
  if k > n then return nil end
  if k > n/2 then k = n - k end       --   (n k) = (n n-k)
  numer, denom = 1, 1
  for i = 1, k do
    numer = numer * ( n - i + 1 )
    denom = denom * i
  end
  return numer / denom
end
\end{luacode}
\begin{document}
Test 1: $\displaystyle\sum\limits_{k=1}^{100} k = \directlua{%
  tex.print(LuaSum(1, 100,  function(k) return k end ))}$

Test 2: $\displaystyle\sum\limits_{k=0}^{5} \dbinom{5}{k} = 
  \directlua{tex.print(LuaSum(0, 5,  function(k) return Binomial(5,k) end ))}$
\end{document}

With return numer // denom you'll get the integer 32 instead of the floating number ...

enter image description here

1
  • See edit ... with binomial Commented yesterday
9

Have you tried the package numerica ?

enter image description here

\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{amsmath}
\usepackage{numerica}

\begin{document}

Test 1:
\[
\sum_{k=1}^{100} k
= \eval*{\sum_{k=1}^{100} k}
\]

Test 2:
\[
\sum_{k=0}^{5} \binom{5}{k}
= \eval*{\sum_{k=0}^{5} \binom{5}{k}}
= 2^5
\]

\end{document}

Edit 1 with a table of values

enter image description here

\documentclass[margin=5pt, varwidth]{standalone}

\usepackage{amsmath}
\usepackage{numerica}
\usepackage{numerica-tables}

\begin{document}

% Table of values for S(n) = \sum_{k=1}^{n} k, for n={1,..,10}
% Key point:
% - rvar is the row variable
% - rstop is how far we go
% - [n=1] gives the initial value of the row variable

\begin{table}[h]
\centering
\nmcTabulate[
  rvar=n,
  rstop=10,
  rstep=1
]{ \sum_{k=1}^{n} k }[n=1]

\end{table}

\end{document}
6
  • interesting. it looks like a nice package. (may not satisfy the speed desideratum, though.) Commented 2 days ago
  • it is ! it reminds me of mapple integration in scientific words... in the 20th century :) Commented 2 days ago
  • @cfr It is not ideal because its \eval function cannot expand \fpeval. For example, \eval{$1 + \fpeval{pi}$} would output !!! Unknown token \fpeval in:formula. !!!. Secondly, it uses the \reuse command to store a value, which is less convenient than \fpset in expl3. Commented 2 days ago
  • 1
    @JeT I did not know that yet. But very interesting. It's good that you also included a table; that immediately gives me some ideas. Commented 2 days ago
  • 1
    PS: I also saw a shortcut Test 1a: \eval{$\displaystyle\sum_{k=1}^{100} k$} Commented 2 days ago
8

You can use xintexpr package

\documentclass{article}
\usepackage{xintexpr}
\newcommand{\myfrac}[1]{\xintTeXsignedFrac{\xinteval{reduce(#1)}}}
\usepackage{amsmath}
\begin{document}
\[1 + 2 + \cdots + 100=\myfrac{add(x, x = 1..100)}.\]
\[1 + \dfrac{1}{2} + \cdots + \dfrac{1}{50}=\myfrac{add(1/x, x = 1..50)}.\]
\[1 + \dfrac{1}{2^2} + \cdots + \dfrac{1}{50^2}=\myfrac{add(1/x^2, x = 1..50)}.\]
\end{document} 

enter image description here

I tried with Mathematica

enter image description here

2
  • Oha, seems to be the inofficial secret LaTeX-CAS. :() But the manual is hard to read... BTW: I opened a xint-thread here: tex.stackexchange.com/questions/758988/… Commented yesterday
  • 1
    @cls from looking at manual add(1/x, x=3, 5, 11) works took, it is not only over a range a..b. Commented 18 hours ago
7

I will delete this later. Probably.

\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{amsmath}
\ExplSyntaxOn
\cs_new:Npn \cis_eval_sum:n #1 {}
\cs_new_protected:Npn \cis_eval_real:nnnn #1#2#3#4 
{
  \fp_zero:N \l_tmpa_fp
  \cs_set:Npn \cis_eval_sum:n ##1 
  {
    \fp_set:Nn #2 {##1}
    \fp_add:Nn \l_tmpa_fp {#1}
  }
  \int_step_function:nnN {#3}{#4} \cis_eval_sum:n
  \fp_to_decimal:N \l_tmpa_fp
}
\cs_new_protected:Npn \cis_eval_ints:nnnn #1#2#3#4 
{
  \int_zero:N \l_tmpa_int
  \cs_set:Npn \cis_eval_sum:n ##1 
  {
    \cs_set:Npn #2 {##1}
    \int_add:Nn \l_tmpa_int {#1}
  }
  \int_step_function:nnN {#3}{#4} \cis_eval_sum:n
  \int_to_arabic:n {\l_tmpa_int}
}
\NewDocumentCommand \Sum { smmmm }
{
  \group_begin:
  \IfBooleanTF {#1}
  {
    \cis_eval_ints:nnnn {#2}{#3}{#4}{#5}
  }{                                   
    \cis_eval_real:nnnn {#2}{#3}{#4}{#5}
  }
  \group_end:
}
\ExplSyntaxOff
\begin{document}
Test 1: $\displaystyle\sum\limits_{k=1}^{100} k = \Sum{\k}{\k}{1}{100}$

\newcommand\binomial[2]{\fpeval{fact(#1)/(fact(#2)*fact(#1-#2))}}
Test 2: $\displaystyle\sum\limits_{k=0}^{5} \dbinom{5}{k}
= \Sum{  \binomial{5}{\k}  }{\k}{0}{5} =2^5 = \fpeval{2^5}$

Test 2: $\displaystyle\sum\limits_{k=0}^{5} \dbinom{5}{k}
= \Sum*{  \binomial{5}{\kyw}  }{\kyw}{0}{5} =2^5 = \fpeval{2^5}$
\end{document}
2
  • Why 'delete'. I think it is good. Commented Jan 28 at 22:47
  • @cis because somebody will write a proper answer. Commented Jan 28 at 23:06
5

I know nothing about CAS systems, nor am I sure I performed the the examples correctly, but one possibility is to transfer the LaTeX calculations to a language more appropriate for mathematical computation, such as R or Python, and let LaTeX handle the formatting through Quarto markdown. I haven't tested it in this case, but it should faster, and IMHO easier to read and edit if you are used to these languages.

If you want to see what LaTeX code is produced to render the images showed, just change format: pdf to format: latex in the header or add keep-tex: true.

You can also explore how to insert the calculations directly into a pure LaTeX code using knitr or Sagetex, but indeed is easier with Quarto.

---
format: pdf
execute:
  echo: false
documentclass: standalone
classoption: [margin=5pt, varwidth]
pdf-engine: lualatex
---

With **R** and Lua\LaTeX:  \bigskip


```{r, cuentas, eval=FALSE}
start <- min(k) 
end <- max(k)
sumint <- sum(k)
```

```{r}
k <- 1:100
```
```{r, cuentas, eval=TRUE}
```

Test 1: \boxed{\sum_{k=`{r} start`}^{`{r} end`} k = `{r} sumint`}\par\bigskip

```{r}
k <- 0:5
```
```{r, cuentas, eval=TRUE}
```

Test 2: \boxed{\sum_{k=`{r} start`}^{`{r} end`} \binom{`{r} end`}{k} = `{r} sum(choose(max(k),k))` = 2^{`{r} end`} = `{r} 2^end`}\par\bigskip


```{r}
k <- 7:13
```
```{r, cuentas, eval=TRUE}
```

Test 3: \boxed{\sum_{k=`{r} start`}^{`{r} end`} \binom{`{r} end`}{k} = `{r} sum(choose(max(k),k))` = 2^{`{r} end-1`} = `{r} 2^(end-1)`}\par\bigskip

with R

---
format: pdf
execute:
  echo: false
# jupyter: python3 # by defaul if python first
documentclass: standalone
classoption: [margin=5pt, varwidth]
pdf-engine: lualatex
---

With Python and Lua\LaTeX:  \bigskip


```{python}
import math
```

```{python}
start = 1
end = 100
sum_int = sum(range(start, end + 1))
```

Test 1:  \boxed{\sum_{k=`{python} start` }^{`{python} end`} k = `{python} sum_int`}\par\bigskip 


```{python}
start = 0
end = 5
sum_binomial = sum(math.comb(end, k) for k in range(end+1))
potencia = 2**end
```

Test 2: \boxed{\sum_{k=`{python} start`}^{`{python} end`} \binom{`{python} end`}{k} = `{python} sum_binomial` = 2^{`{python} end`} = `{python} potencia`}\par\bigskip

```{python}
start = 7
end = 13
sum_binomial = sum(math.comb(end, k) for k in range(start, end))
potencia = 2**(end-1)
```

Test 3: \boxed{\sum_{k=`{python} start`}^{`{python} end`} \binom{`{python} end`}{k} = `{python} sum_binomial` = 2^{`{python} end-1`} = `{python} potencia`}\par\bigskip


```{python}
start = 1
end = 10
sum_real = sum(1 / k for k in range(start, end + 1))
```

Test 4: \boxed{\sum_{k=`{python} start`}^{`{python} end`} \frac{1}{k} \approx `{python} round(sum_real, 4)`} 

with Python

2
  • Maybe add a link to an entrance point to Quarto, I did find after much searching quarto.org which I found a bit intimidating, perhaps there is some canonical introduction somewhere? Commented 14 hours ago
  • @user691586 Quick way to start: (1) Install R and Phyton (and whatever that you will use in a Quarto Document (2) install Rstudio, if you have not a LaTeX distro already installed, install also TinyTex from a R console (3) In Rstudio, Help > Markdown Quick Reference (4) Now go to File > New File > Quarto Document > select PDF and click on "Create" > Just play with the example document, experiment > Click on Render (the buttom with a blue arrow) (5) Revisit quarto.org, AFAIK the complete help is only there. Commented 6 hours ago

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.