# Calculate Pi unto a point using the Nilakantha series

Your task: given a nonzero positive number i, calculate pi using the Nilakantha series unto i terms.

The Nilakantha series is as follows:

$$\text 3 + \frac{4}{2*3*4} - \frac{4}{4*5*6}+\frac{4}{6*7*8} - ...$$

3 is the first term, 4/2*3*4 is the second, -4/4*5*6 is the third, and so on.

Notice that for the nth term:

• $$\text S_1 = 3$$
• $$\text S_n = \frac{4 \times (-1)^n}{2n \times (2n-1) \times (2n-2)}$$
• The approximation of pi by summing up these terms is $$\text S_1 +\text S_2\text + … +\text S_n$$

Test cases:

In = Out

1 = 3
2 = 3.16666666667
3 = 3.13333333333
4 = 3.1452381


Notice the pattern of the numbers approximating towards pi.

Floating point issues are OK.

This is so shortest answer wins!

EDIT: by default this is 1-indexed, but if you want 0-indexed no problem, just mention it. And even infinitely printing the approximations with no input is Okay.

• May i by 0-based (e.g. 0=3, 1=3.166..., 2=3.133..., 3=3.145...)? Also, is there a reason for overwriting the default sequence rules? Or is outputting an infinite list of all items also allowed, without taking an input? Sep 15 at 13:51
• If you want to, ok. For the sequence issue, here we’re trying to calculate a number using a series, not the terms of the series. Sep 15 at 17:15
• But since you’ve posted an answer assuming it already, yeah you can. Sep 15 at 17:42
• Is it okay to output rational numbers rather than floating point? Sep 15 at 19:51
• Use \times instead of * in mathjax
– qwr
Sep 16 at 4:15

# Python 3.8 (pre-release), 38 bytes (@xnor)

f=lambda n,i=.5:i//n/n or 2/i-f(n,i+1)


Try it online!

### Python 3.8 (pre-release), 40 bytes (@xnor)

f=lambda n,i=1:i//2//n/n or 4/i-f(n,i+2)


Try it online!

### Python, 45 bytes

f=lambda n,s=1:4/(2*s-1)-(s//n/s or f(n,s+1))


Attempt This Online!

1-based. n has to be positive.

### Python, 50 bytes

f=lambda n,s=0:n and f(n-1,4/(n+n-1)-s-0**s/n)or s


Attempt This Online!

This uses $$\\frac 4 {2x(2x+1)(2x+2)} =\frac 1 x + \frac 1 {x+1} - \frac 4 {2x+1} \$$ and that inside the full sum the first two terms cancel.

1-based. Can handle 0.

# Python 3.8 (pre-release), 45 bytes (@xnor)

f=lambda n:0**n*3or(-1)**n/n/(n-~n)/~n+f(n-1)


Try it online!

### Python, 50 bytes

f=lambda n:0**n*3or 1/(n|1)/(~n-n)/(n%-2^n)+f(n-1)


Attempt This Online!

0-based.

• Nice methods! It looks like your last one can be simplified to 45 bytes, and probably this can be made shorter.
– xnor
Sep 15 at 21:50
• @xnor thanks, looks like I had over engineered that one. Sep 15 at 22:03
• Shifting around your first one for 42 bytes
– xnor
Sep 15 at 22:13
• 38 bytes
– xnor
Sep 15 at 22:17
• Dammit @xnor I thought I was reasonably good at golfing. Sep 15 at 22:21

# Jelly, 13 bytes

RḤrƝP€4÷Ṛḅ-+3


A monadic Link that accepts a positive integer and yields the approximation (up to the floating point accuracy).

Try it online!

### How?

RḤrƝP€4÷Ṛḅ-+3 - Link: positive integer, n  e.g. 4
R             - range                           [1,2,3,4]
Ḥ            - double                          [2,4,6,8]
Ɲ          - for neighbours:
r           -   inclusive range               [[2,3,4],[4,5,6],[6,7,8]]
P€        - product of each                 [24,120,336]
4÷      - four divided by those           [1/6,1/30,1/84]
Ṛ     - reverse                         [1/84,1/30,1/6]
ḅ-   - convert from base -1            sum([1/84,-1/30,1/6])=0.14523809523809522
+3 - add three                       3.14523809523809522


# JavaScript (ES6), 32 bytes

This version is based on @loopy-walt's answer, golfed by @xnor.

f=(n,i=.5)=>i<n?2/i-f(n,i+1):1/n


Try it online!

# JavaScript (ES6), 39 bytes

f=n=>--n?f(n)+(4-n%2*8)/(n+=n)/++n/~n:3


Try it online!

### Commented

f = n =>          // f is a recursive function taking the input n
--n ?             // decrement n; if it's not 0:
f(n) +          //   do a recursive call and add:
(4 - n % 2 * 8) //     -4 if n is odd, +4 otherwise
/ (n += n)      //     divided by 2n
/ ++n           //     divided by 2n + 1
/ ~n            //     divided by -(2n + 2)
:                 // else:
3               //   end of recursion: return the integer part


# Factor + koszul math.unicode,  68 64 bytes

[ ""3 rot [0,b) [ -1^ 4 reach Π / * + [ 2 v+n ] dip ] each ]


Attempt This Online!

0-indexed. Note the string literal has the control characters 2, 3, and 4 embedded, making it equivalent to the sequence { 2 3 4 }. You can see these characters on ATO.

              ! 3
""            ! 3 { 2 3 4 }
3             ! 3 { 2 3 4 } 3
rot           ! { 2 3 4 } 3 3
[0,b)         ! { 2 3 4 } 3 { 0 1 2 }
[ ... ] each     <<for each element in { 0 1 2 }...>>
<<first iteration>>
! { 2 3 4 } 3 0
-1^           ! { 2 3 4 } 3 1
4             ! { 2 3 4 } 3 1 4
reach         ! { 2 3 4 } 3 1 4 { 2 3 4 }
Π             ! { 2 3 4 } 3 1 4 24
/             ! { 2 3 4 } 3 1 1/6
*             ! { 2 3 4 } 3 1/6
+             ! { 2 3 4 } 3+1/6
[ 2 v+n ] dip ! { 4 5 6 } 3+1/6
<<second iteration>>
! { 4 5 6 } 3+1/6 1
<<and so on>>


# Vyxalḋ, 19 bytes

ƛune4*nd:‹:‹**/;∑3+


ḋ flag to print rationals in their decimal form

Explanation:

ƛune4*nd:‹:‹**/;∑3+
ƛ              ;      Map lambda through inclusive range 1 to input
une                  Push -1 to the power n
4*                Multiply by 4 and push that
nd:             Multiply n by 2 and duplicate
‹:           Decrement and duplicate
‹**        Decrement and push product of denominator
/       Divide 4*(-1)**n by 2n*(2n-1)*(2n-2)
∑3+   Sum list and add 3



Try it Online!

# R, 51 bytes

\(k,n=2:k*2)if(k>1,3+sum(4*1i^n/n/(n-1)/(n-2)),3)


Attempt This Online!

Uses the fact that $$\(-1)^n=i^{2n}\$$.

### R, 51 bytes

\(k,n=2:k)if(k>1,3+sum((-1)^n/n/(2*n-1)/(n-1)),3)


Attempt This Online!

Uses the formula but with simplifying the fraction to $$\\frac{(-1)^n}{n(2n-1)(n-1)}\$$.

# 05AB1E, 20 16 bytes

3λè®Nm4*N·2Ý-P/+


Outputs the 1-based $$\n^{th}\$$ value (by starting with $$\a(0)=3\$$ and where $$\a(1)\$$ is calculated as $$\3\$$ as well).

Explanation:

 λ         # Start a recursive environment,
è        # to calculate a(input)
# (which is output implicitly afterwards)
3          # Start with a(0)=3
# Where every following a(n) is calculated by:
#  (implicitly push the previous term a(n-1))
®Nm     #  Push (-1) to the power n
4*   #  Multiply it by 4
N·      #  Push 2n
2Ý    #  Push list [0,1,2]
-   #  Subtract each from the 2n: [2n,2n-1,2n-2]
P  #  Take the product of this triplet: 2n*(2n-1)*(2n-2)
/       #  Divide the earlier 4*(-1)**n by this (2n*(2n-1)*(2n-2))
+      #  Add it to the previous term a(n-1)


# C (gcc), 80 $$\\cdots\$$ 71 70 bytes

i;float s,m;float f(n){for(m=4,s=i=3;i++<2*n;s-=m/i/~-i/(i++-2))m=-m;}


Try it online!

Saved 5 6 bytes thanks to Kevin Cruijssen!!!
Saved 4 bytes thanks to Arnauld!!!

• 66 bytes Sep 17 at 8:54

# Desmos, 36 bytes

f(x)=3+∑_{n=2}^x(-1)^n/n(2nn-3n+1)


Try it on Desmos!

Near direct copy of the definition, simplified and rearranged only a little bit. 1 indexed.

Breakdown:

f(x)=3+∑_{n=2}^x(-1)^n/n(2nn-3n+1)  full function

f(x)=                               function definition (not sure if required)
3+                             3 plus
∑                            The sum from
_{n=2}                        n=2
^x                      to n=x
(note that this defaults to 0 if x is less than 2)
of
(-1)^n                -1 when n is odd, 1 if n is even
/               divided by
n(2nn-3n+1)    2n^3-3n^2+n


# Vyxalḋ, 16 bytes

4ÞNÞ∞d2ʀv+vΠ/3p¦


Try it Online! Outputs as an infinite list.

Because Lyxal's sus this code only works for <v2.13.3 and hopefully future versions. The link contains a fix that's a byte longer.

4                # 4
ÞN              # [4, -4, 4, -4...]
/    # Each divided by...
Þ∞            # [1, 2, 3...]
d           # doubled [2, 4, 6...]
2ʀ         # [0, 1, 2]
v+       # Add to each [[2, 3, 4], [4, 5, 6]...]
vΠ     # Take the product of each
3p  # Prepend a 3
¦ # Take the cumulative sums


# Python 3, 49 bytes

f=lambda n:n-1and(-1)**n/(2*n*n-n)/~-n+f(n-1)or 3


Try it online!

-5 bytes thanks to Mukundan314

• this fails for me Sep 16 at 10:28
• @py3programmer It seems to work on TiO. Could you be more specific? Sep 16 at 12:35
• I think it's because of 1and in the code. Sep 16 at 12:36
• Can you send the link on which it works on? Sep 16 at 12:37
• @py3programmer The link is in the post, if you'd like to try for yourself. As far as I am aware, 1and is legal syntax. Sep 16 at 12:37

# Wolfram Language (Mathematica), 36 35 bytes

3.-Sum[(-1)^n/(2n^3+3n^2+n),{n,#}]&


Try it online!

Alternatively, and more interestingly, we can express the partial sums in terms of a Lerch transcendent: 36 bytes

Pi+(-1)^#(1/#-2LerchPhi[-1,1,#+.5])&


Try it online!

# Fig, $$\18\log_{256}(96)\approx\$$ 14.816 bytes

+3S\n2@Nere+r3hax4


Try it online!

Port of Vyxal. Beats both that and osabie, 1.8 bytes longer than Jelly. 0-indexed.

+3S\n2@Nere+r3hax4
ax  # Range [1, n]
h    # Double
r3     # [0, 1, 2]
e+       # Add ^ to every element of ^^
er         # Product of each element
@N           # Negate
n2             # Every other element
\             4 # Four divided by ^
S                # Sum
+3                 # Add 3


# Charcoal, 22 21 bytes

Try it online! Link is to verbose version of code. Explanation:

   Ｎ                     Input n as a number
Ｅ                      Map over implicit range
ι                   Current value
⎇                    If nonzero then
ι              Current value
﹪               Modulo
²             Literal integer 2
⊗                Doubled
⊖                 Decremented
∕                  Divided by
ι         Current value
×          Multiplied by
ι       Current value
⊕        Incremented
×           Multiplied by
ι    Current value
⊗     Doubled
⊕      Incremented
³   Otherwise literal integer 3
Σ                       Take the sum
Ｉ                        Cast to string
Implicitly print


Edit: Saved 1 byte by adpating @pajonk's simplification.

# x86 32-bit machine code, 37 33 bytes

D9 E8 D8 C0 D8 C0 D9 E8 F9 D9 E8 D8 F1 D9 E8 DE C2 D8 F1 D8 C0 F5 72 F5 DE E2 E2 ED DD D8 D9 E1 C3


Try it online!

Following the fastcall calling convention, this takes a number i in ECX and returns the sum of the first i terms on the FPU register stack.

In assembly:

f:  fld1
fadd st(0), st(0)
fadd st(0), st(0)   # Example execution for 2nd iteration
fld1                # FPU register stack (left is bottom):
stc                 # -3   2   (before)
r:  fld1                # -3   2   1
fdiv st(0), st(1)   # -3   2   1/2
ir: fld1                # -3   2   1/2   1
faddp st(2), st(0)  # -3   3   1/2
fdiv st(0), st(1)   # -3   3   1/(2*3)
fadd st(0), st(0)   # -3   3   2/(2*3)
cmc                 #[Repeat the 4 instructions above, using an inner loop:
jc ir               # -3   3   2/(2*3)   1
# -3   4   2/(2*3)
# -3   4   2/(2*3*4)
# -3   4   4/(2*3*4)
fsubrp st(2), st(0) # 3+4/(2*3*4)   4
loop r
fstp st(0)
fabs
ret


Each iteration of the outer loop computes one term $$\\frac4{2n(2n+1)(2n+2)}\$$ and combines it in using the reverse-subtract instruction; as in my answer to a related problem, this handles the alternating signs, but leaves the result with the wrong sign for even i, which is corrected for by taking the absolute value at the end (because all the correct results are positive).

The first iteration, if left the same as later iterations, would contain a division by 0. This is prevented by setting CF to 1 at the beginning, so that the inner loop executes once instead of twice during the first iteration, and it computes $$\\frac2{1\cdot2}\$$ instead.

# Raku, 36 bytes

[\+] 3,{-4*($*=-1)/[*] ^3+2*++$}...*


Try it online!

This is an expression for the infinite sequence of partial sums. 3 is the first term of the sequence, and the curly braces enclose a generating expression for the subsequent terms.

• The dividend is -4 * ($*= -1). The $ here is an anonymous state variable. The *= -1 causes it to alternate between -1 and 1. (The first time the expression is evaluated, it's undefined, but since it's being multiplied, it defaults to the multiplicative identity element 1.) Multiplying that by -4 produces the sequence of dividends 4, -4, 4, -4, ....
• The divisor is [*] ^3 + 2 * ++$. $ here is another anonymous state variable which the preincrement operator ++ causes to take on the values 1, 2, 3, ..., as it's evaluated for each term of the sequence. Multiplying that by 2 produces 2, 4, 6, .... Those even numbers are added to the range ^3, which means the integers from 0 to 2, producing a sequence of ranges 2, 3, 4, 4, 5, 6, 6, 7, 8, .... Then [*] multiplies those numbers together.

[\+] produces the sequence of partial sums of the terms.