15
\$\begingroup\$

based off my previous challenge, this wikipedia article, and a Scratch project

Your task: given i, calculate \$\pi\$ till i terms of the Gregory-Leibniz series.

The series:

$$\pi=\frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\frac{4}{9}-...$$

Here, 4/1 is the first term, -4/3 is the second, 4/5 is the second and so on.

Note that for the nth term,

  • $$\text S_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$
  • $$\pi_n = \text S_1 + \text S_2 + ... + \text S_n,$$ where \$\pi_n\$ is \$\pi\$ approximated to \$n\$ terms.

Test cases:

In - Out
1 - 4
2 - 2.66666667
3 - 3.46666667
4 - 2.8952381

Floating point issues are OK.

You may not calculate infinite terms of pi using this as we are calculating a number rather than terms of a series here.

This is , so shortest answer wins!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ You may not calculate infinite terms of pi [...] -> Does that mean that we can't use standard sequence I/O? If so, I don't understand why. \$\endgroup\$
    – Arnauld
    Sep 19 at 13:20
  • \$\begingroup\$ @Arnauld I think what he meant to say is that the challenge is to output the terms of the Gregory Leibniz sequence, and not the (potentially infinite) digits of pi itself. \$\endgroup\$ Sep 19 at 13:22
  • \$\begingroup\$ Nope. Here pi is being calculated by adding up the terms of the series. So you add up the terms, and then print the approx. of pi when summing up \$\endgroup\$ Sep 19 at 13:24
  • 1
    \$\begingroup\$ I don't understand why we cannot output \$\pi_n\$ with standard sequence I/O (this would mean also allowing output of approximations of \$\pi\$ up to \$n\$ terms or outputting more approximations without end). \$\endgroup\$
    – pajonk
    Sep 20 at 5:26
  • \$\begingroup\$ Normally, I would have let you as you'd be printing terms of a series, but here we are printing approximations. Why should we print all approximations to a certain term? When calculating pi, we aim for the most accurate, not keeping a log of inaccurate periods. \$\endgroup\$ Sep 20 at 7:01

28 Answers 28

5
\$\begingroup\$

Python 3, 36 35 bytes

f=lambda n,k=1:n and 4/k-f(n-1,k+2)

Try it online!

-1 thanks to Mukundan314.

\$\endgroup\$
2
5
\$\begingroup\$

05AB1E, 14 9 bytes

L·<z··R®β

-5 bytes porting @JonathanAllan's Jelly answer

Try it online or verify all test cases.

Original 14 bytes answer:

0λè®N>m4*N·</+

Try it online or verify the infinite sequence.

Explanation:

L          # Push a list in the range [1, (implicit) input]
 ·         # Double each value: [2,4,6,...,2n]
  <        # Decrease each by 1: [1,3,5,...,2n-1]
   z       # Calculate 1/z for each: [1,1/3,1/5,...,1/(2n-1)]
    4*     # Multiply by 4: [4,4/3,4/5,...,4/(2n-1)]
      R    # Reverse the list: [4/(2n-1),...,4/5,4/3,4]
       ®β  # Convert it from a base-(-1) list to a base-10 integer:
           #  (-1)^(n-1)*4/(2n-1) + ... + 1*4/5 + -1*4/3 + 1*4/1
           # (after which the result is output implicitly)

The 14-byter is pretty similar as my 05AB1E answer of the previous challenge.

 λ         # Start a recursive environment,
  è        # to calculate a(input)
           # (which is output implicitly afterwards)
0          # Start with a(0)=0
           # Where every following a(n) is calculated by:
           #  (implicitly push the previous term a(n-1))
   ®N>m    #  Push (-1) to the power (n+1)
       4*  #  Multiply it by 4
   N·<     #  Push 2n-1
   /       #  Divide the earlier 4*(-1)**(n+1) by this (2n-1)
    +      #  Add it to the previous term a(n-1)
\$\endgroup\$
4
\$\begingroup\$

Jelly, 8 bytes

RḤ’4÷Ṛḅ-

A monadic Link that accepts a positive integer, \$n\$, and yields a floating point number, \$\pi_n\$.

Try it online!

How?

RḤ’4÷Ṛḅ- - Link: positive integer, n
R        - range n           -> [1,2,3,...,n]
 Ḥ       - double            -> [2,4,6,...,2n]
  ’      - decrement         -> [1,3,5,...,2n-1]
   4     - 4
    ÷    - divide            -> [4/1,4/3,4/5,...,4/(2n-1)]
     Ṛ   - reverse           -> [4/(2n-1),...,4/5,4/3,4/1]
       - - -1
      ḅ  - convert from base -> (-1)^(n-1)*4/(2n-1)+...+1*4/5+-1*4/3+1*4/1 = pi_n
\$\endgroup\$
4
\$\begingroup\$

C (gcc), 63 60 bytes

float f(n){float m=4,p=1,d=1;for(;n--;d+=2,m=-m)p+=m/d;--p;}

Try it online!

Saved 3 bytes thanks to jdt!!!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ float f(n){float m=4,p=1,d=1;for(;n--;d+=2,m=-m)p+=m/d;--p;} \$\endgroup\$
    – jdt
    Sep 19 at 14:23
  • 1
    \$\begingroup\$ @jdt Nice one - thanks! :D \$\endgroup\$
    – Noodle9
    Sep 19 at 14:40
3
\$\begingroup\$

Python 3, 41 39 bytes

f=lambda x:x and(x%2*4-2)/(x-.5)+f(x-1)

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Desmos, 30 bytes

f(n)=∑_{k=1}^n4(-1)^k/(1-2k)

Pretty self-explanatory.

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
11
  • \$\begingroup\$ Congrats - This is my first time seeing a desmos answer... \$\endgroup\$ 2 days ago
  • \$\begingroup\$ @py3programmer If you enjoy them, I got many more! \$\endgroup\$
    – Aiden Chow
    2 days ago
  • \$\begingroup\$ It is true... but I suppose Desmos only works on math-related questions... \$\endgroup\$ 2 days ago
  • \$\begingroup\$ @py3programmer Yeah true, Desmos works really well on math-related decision problems especially. \$\endgroup\$
    – Aiden Chow
    2 days ago
  • \$\begingroup\$ True, because, after all, Desmos is a graphing calculator, but I'm surprised it can be used as a code-golfing language! \$\endgroup\$ 2 days ago
3
\$\begingroup\$

Vyxal , 10 bytes

4ÞNÞ∞d‹/¦i

Try it Online!

4          # 4
 ÞN        # [4, -4, 4, -4, 4, -4...
   Þ∞      # [1, 2, 3, 4, 5, 6...
     d     # [2, 4, 6, 8, 10, 12...
      ‹    # [1, 3, 5, 7, 9, 11...
       /   # [4/1, -4/3, 4/5, -4/7...
        ¦  # Take the cumulative sums of that
         i # Index the input into that
\$\endgroup\$
1
  • \$\begingroup\$ "You may not calculate infinite terms of pi using this as we are calculating a number rather than terms of a series here." \$\endgroup\$
    – Shaggy
    Sep 19 at 21:08
3
\$\begingroup\$

Haskell, 28 bytes

f n=foldr((-).(2/))0[1/2..n]

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Japt -mx, 11 bytes

4*JpU /(UÑÄ

Try it

Without Flags, 11 bytes

DZZ4/°ZÃÔìJ

Try it

4*JpU /(UÑÄ     :Implicit map of each U in the range [0,input)
4*              :Multiply 4 by
  J             :-1
   pU           :Raised to the power of U
      /(        :Divide by
        UÑ      :U times 2
          Ä     :Plus 1
                :Implicit output of sum of resulting array
DZZ4/°ZÃÔìJ     :Implicit input of integer U
Ç               :Map each Z in the range [0,U)
 ±Z             :  Increment Z by itself
   4/           :  Divide 4 by
     °Z         :  Z, prefix incremented
       Ã        :End map
        Ô       :Reverse
         ì      :Convert from digit array in base
          J     :  -1
\$\endgroup\$
2
\$\begingroup\$

R, 31 28 bytes

Edit: -3 bytes thanks to @Dominic van Essen.

\(n,m=2*1:n-1)sum(4i/1i^m/m)

Attempt This Online!

Uses $$ (-1)^{n+1} = -1 \times (-1)^{n} = i^2\times i^{-2n} = i^{-2n+2} = i \times i^{-(2n-1)}$$ And then $$\text S_n = \frac{4 \times (-1)^{n+1}}{2n-1} = \frac{\frac{4i}{i^{2n-1}} }{2n-1} $$

\$\endgroup\$
3
  • \$\begingroup\$ Alternative 28 byte version: \(n)sum(4/(1:n*2-1)*c(1,-1)) (generates a warning for odd n, but still computes the correct answer) \$\endgroup\$
    – JDL
    Sep 20 at 10:38
  • \$\begingroup\$ Nevermind, I can't make it work for n=1 :( \$\endgroup\$
    – JDL
    Sep 20 at 10:49
  • 1
    \$\begingroup\$ 28 bytes (and works for n=1)... \$\endgroup\$ Sep 26 at 11:43
1
\$\begingroup\$

Vyxal , 13 bytes

Flag prints out rationals in their decimal form

ƛ4nd‹/un›e*;∑

Try it Online!

Explanation:

ƛ4nd‹/un›e*;∑
ƛ          ;    Map trough range of input
 4nd‹/          Divide four by 2n-1
      un›e*     Raise -1 to the n+1 and multiply
            ∑   Sum the fractions

Another 13 byter: ƛ4nd‹/k-ni*;∑

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 47 bytes

float f(n){return--n?(4.-n%2*8)/(n-~n)+f(n):4;}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Unicode), 18 bytes SBCS

(4ׯ1*⍳)+.÷(1+2×⍳)

Try it on APLgolf!

A tacit function.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 14 bytes

IΣEN×X±¹ι∕⁴⊕⊗ι

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

   N            Input `n` as a number
  E             Map over implicit range
       ¹        Literal integer `1`
      ±         Negated
     X          Raised to power
        ι       Current value
    ×           Multiplied by
          ⁴     Literal integer `4`
         ∕      Divided by
             ι  Current value
            ⊗   Doubled
           ⊕    Incremented
 Σ              Take the sum
I               Cast to string
                Implicitly print
\$\endgroup\$
1
\$\begingroup\$

Haskell, 36 bytes

f i=g[1,3..i*2]
g(h:t)=4/h-g t
g[]=0

Try it online!

I think it's quite self descriptive due to Haskell feature of describing something.

I try to visualize what g does, pretty simple : taking a list of i denominators but all positive...

[1,      3,      5,      7]
                       4/7
               4/5 -  (4/7)
 4 - ( 4/3 - ( 4/5 -  (4/7)))

hence the signs result alternating
 4 -   4/3 +   4/5 -   4/7
\$\endgroup\$
1
\$\begingroup\$

Factor + koszul math.unicode, 51 bytes

[ [1,b] [ dup 1 + -1^ 4 * swap 2 * 1 - / ] map Σ ]

Try it online!

  • [1,b] [ ... ] map Σ Map each integer in 1..input using [ ... ] and add them together.
  • dup 1 + -1^ 4 * swap 2 * 1 - / Just a straight translation of $$\text S_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$ Here's how the data stack looks arriving at the second term to add together:
       ! 2
dup    ! 2 2
1      ! 2 2 1
+      ! 2 3
-1^    ! 2 -1
4      ! 2 -1 4
*      ! 2 -4
swap   ! -4 2
2      ! -4 2 2
*      ! -4 4
1      ! -4 4 1
-      ! -4 3
/      ! -1-1/3
\$\endgroup\$
1
\$\begingroup\$

x86 32-bit machine code, 23 bytes

D9 EE D9 E8 D9 E8 D8 C0 DC E9 D8 F1 DE E2 E2 F4 DD D8 D8 C0 D9 E1 C3

Try it online!

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

This code creates −2/1, −2/3, −2/5, ..., and combines them using the reverse-subtract instruction. This is equivalent to negating the running total before adding each term; this handles the alternating signs, but leaves the result with the wrong sign for odd n, which is corrected for by taking the absolute value at the end (because all the correct results are positive). The value is also doubled at the end.

In assembly:

                        # Example execution for i=2
                        # FPU register stack (left is bottom):
f:  fldz                # 0
    fld1                # 0   1
r:  fld1                # 0   1   1
    fadd st(0), st(0)   # 0   1   2
    fsub st(1), st(0)   # 0  -1   2
    fdiv st(0), st(1)   # 0  -1  -2/1
    fsubrp st(2), st(0) # -2/1  -1
    loop r              #[The loop executes again:
                        # -2/1  -1   1
                        # -2/1  -1   2
                        # -2/1  -3   2
                        # -2/1  -3  -2/3
                        # -2/3+2/1  -3            ]
    fstp st(0)          # -2/3+2/1
    fadd st(0), st(0)   # -4/3+4/1
    fabs                # -4/3+4/1   (but for odd n, this fixes the sign)
    ret
\$\endgroup\$
1
\$\begingroup\$

Fortran (GFortran), 60 bytes

function a(j)
do i=1,j
a=a+4.0*(-1)**(i+1)/(2*i-1)
enddo
end

Try it online!

Mostly just exploiting implicit typing so no need to declare variable types. Also saves 1 byte by removing the space between end and do.

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Sep 20 at 14:53
1
\$\begingroup\$

BQN, 9 bytes

-´4÷1+2×↕

Try it at BQN online!

Explanation

-´4÷1+2×↕
        ↕  Range [0, n)
      2×   Double each number
    1+     Add 1 to each number
  4÷       Divide 4 by each number
-´         Right fold on subtraction
\$\endgroup\$
1
\$\begingroup\$

Husk, 10 bytes

Ḟ`-m`/4↑İ1

Try it online!

Explanation

Husk's reversed operand order for subtraction and division really hurts here.

Ḟ`-m`/4↑İ1
        İ1  Infinite list of positive odd numbers
       ↑    Take the first N elements, where N is the program's argument
   m        For each element,
    `/4     divide 4 by it
Ḟ           Right-fold the resulting list
 `-         on subtraction
\$\endgroup\$
1
\$\begingroup\$

MATLAB, 34 bytes

f=@(n)sum(4./[1:4:2*n,-(3:4:2*n)])

An anonymous function that makes an array of [ 1 5 9 ... -3 -7 -11 ...], member-wise divides 4 by the array and then sums the result.

Test:

arrayfun(f, 1:4)
  ans = 4.0000    2.6667    3.4667    2.8952
\$\endgroup\$
1
\$\begingroup\$

Excel, 51 bytes

=LET(s,SEQUENCE(A1),SUM(IF(ISODD(s),4,-4)/(2*s-1)))

Input is in the cell A1. Output is wherever the formula is.

  • LET(s,SEQUENCE(A1) defines s to be an array of numbers from 1 to the value in A1. This is what lets us calculate the first n terms.
  • IF(ISODD(s),4,-4) creates an array of the same sized filled with 4, -4, 4, -4, ...
  • (2*s-1) creates an array of the same size filled with 1, 3, 5, 7, ...
  • SUM(IF(~)/(~)) divides the first array by the second (giving us each term in the sequence) and then adds them up.

SCreenshot

\$\endgroup\$
1
\$\begingroup\$

Rust, 62 bytes

fn f(n:f32,k:f32)->f32{if n==0.{return 4./k}4./k-f(n-1.,k+2.)}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Raku, 26 bytes

[\+] (4,-*...*)Z/(1,3...*)

Try it online!

This is an expression for the infinite sequence of partial sums.

  • (4, -* ... *) is the sequence 4, -4, 4, -4, ....
  • (1, 3 ... *) is the sequence 1, 3, 5, ....
  • Z/ zips those two sequences together using division.
  • [\+] produces the sequence of partial sums.
\$\endgroup\$
0
\$\begingroup\$

Pyth, 11 bytes

*4smc^_1dhy

Test suite

Explanation:
*4smc^_1dhy   | Full code
*4smc^_1dhydQ | with implicit variables
--------------+
   m        Q | For each d from 0 to input:
    c^_1dhyd  |  (-1)^d/(2d+1)
  s           | Sum the results
*4            | Print sum * 4
\$\endgroup\$
0
\$\begingroup\$

Wolfram Language (Mathematica), 26 bytes

Tr[4I^#/I/#&[2Range@#-1]]&

Try it online!

Unnamed function that takes a positive integer argument and returns an exact fraction (the TIO footer shows both the output fraction and its decimal equivalent). Managed to beat the super straightforward Sum[-4(-1)^j/(2j-1),{j,#}]& by one byte by using powers of the complex unit I instead of powers of -1.

\$\endgroup\$
0
\$\begingroup\$

Math++, 49 bytes

?>x
1>a
1>b
k+b*4/a>k
a+2>a
-b>b
x-1>x
4+5*!x>$
k
\$\endgroup\$
0
\$\begingroup\$

Fig, \$11\log_{256}(96)\approx\$ 9.054 bytes

S\n2@N{hax4

Try it online!

I spent so long golfing this just to beat Husk. No hax used.

S\n2@N{hax4
        ax  # Range [1, n]
       h    # Double
      {     # Subtract 1
    @N      # Negate
  n2        # Every other element
 \        4 # 4 divided by the list
S           # Sum
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.