2.2 Using variables

 

2.1 Current value reference


Use the Maclaurin series method to calculate e:

e=1+1/1!+1/2!+1/3!+…

SPL

A
1 =to(20)
2 =nf=1,1+A1.sum((nf*=~,1/nf) )

The symbol ‘~’ means the current members while looping through sequences. In the calculation process, first define a variable nf, and then update this variable while looping. In this way, the result can be calculated by simply calculating the factorial of 20 once.

SQL

WITH factorial_table (n, fact) AS (
  SELECT 1, 1 FROM dual
  UNION ALL
  SELECT n + 1, fact * (n + 1) FROM factorial_table
  WHERE n < 20 )
SELECT 1 + SUM(1/fact) AS e_approximation
FROM factorial_table;

Python

from math import factorial
s = pd.Series([i for i in range(1,21)])
e = s.apply(lambda x:1/factorial(x)).sum()+1

The calculation process of Python is somewhat complicated. Because Python cannot keep the factorial result while looping, it needs to calculate the factorial of each number from 1 to 20.


2.3 Sequence number reference
Example codes for comparing SPL, SQL, and Python