19
\$\begingroup\$

We all know that the Euler's number, denoted by e, to the power of some variable x, can be approximated by using the Maclaurin Series expansion:

Maclaurin series expansion of e^x

By letting x equal 1, we obtain

Maclaurin series expansion of e

Challenge

Write a program in any language which approximates Euler's number by taking in an input N and calculates the series to the N-th term. Note that the first term has denominator 0!, not 1!, i.e. N=1 corresponds to 1/0!.

Scoring

Program with least amount of bytes wins.

\$\endgroup\$
  • 7
    \$\begingroup\$ Given large enough N the results will be the same if using a finite precision floating point number. Is that behaviour acceptable or does the result have to progressively get more accurate as N approaches infinity? \$\endgroup\$ – FryAmTheEggman Jun 10 '16 at 20:12
  • 11
    \$\begingroup\$ Some test cases would be neat. \$\endgroup\$ – Lynn Jun 10 '16 at 20:15
  • 6
    \$\begingroup\$ (This kind of issue is preferably resolved in the sandbox – if you post your challenges there first, golfers will give useful feedback.) \$\endgroup\$ – Lynn Jun 10 '16 at 20:27
  • 2
    \$\begingroup\$ Is x^n the nth term or the (n+1)th? \$\endgroup\$ – msh210 Jun 10 '16 at 20:31
  • 3
    \$\begingroup\$ I personally despise it, but there are people who refer to the term at index 0 as zeroth term. Independently of our thoughts on that matter, the question should be as clear as possible. Also, a few test cases to verify that the solutions are working correctly, would be very helpful. \$\endgroup\$ – Dennis Jun 11 '16 at 0:04

36 Answers 36

11
\$\begingroup\$

Jelly, 5 bytes

R’!İS

Try it online!

How it works

R’!İS  Main link. Argument: n

R      Yield the range [1, ..., n].
 ’     Map decrement over the list.
  !    Map factorial over the list.
   İ   Map inverse over the list.
    S  Compute the sum.
\$\endgroup\$
13
\$\begingroup\$

Wistful-C - 336 bytes

My first real wistful- program! There is actually a little golfing I did, with using someday instead of wait for because the first had a shorter length.

if only <stdio.h> were included...
if only int f were 1...
if only int N were 0...
wish for "%d",&N upon a star
if only int i were 0...
if only double e were 0...
someday i will be N...
        if only e were e+1./f...
        if only i were i+1...
        if only f were f*i...
*sigh*
wish "%f\n",e upon a star
if wishes were horses...
\$\endgroup\$
  • \$\begingroup\$ I was told that you don't need to include <stdio.h> \$\endgroup\$ – Leaky Nun Jul 28 '16 at 6:03
  • \$\begingroup\$ Does someday i were N... work instead of someday i will be N...? \$\endgroup\$ – Leaky Nun Jul 28 '16 at 6:16
10
\$\begingroup\$

Pyth, 7 6 bytes

smc1.!

Try it here.

 m      map over range 0..input:
    .!  factorial
  c1    1 / ^
s       sum

Thanks to FryAmTheEggman for a byte!

\$\endgroup\$
8
\$\begingroup\$

TI-84 BASIC, 12 15 14

Input N
Σ(A!⁻¹,A,0,N

TI is a tokenized language (bytes are counted via tokens, not individual characters).

\$\endgroup\$
  • 1
    \$\begingroup\$ The cited meta post has 11 upvotes and 10 downvotes. That's not a consensus. Ans is not a valid input format, so only the 15-byte version is valid. \$\endgroup\$ – Mego Jun 11 '16 at 2:09
  • \$\begingroup\$ fair enough; editing... \$\endgroup\$ – No Name Jun 11 '16 at 2:22
  • 1
    \$\begingroup\$ Ans has always been the default input format here at PPCG (look through my old TI answers), and more people agree than disagree to that, so don't get bullied into changing your answer. \$\endgroup\$ – Timtech Jun 11 '16 at 13:56
  • 2
    \$\begingroup\$ @MickLH that's not the dispute here. Besides, these are 8-bit bytes. \$\endgroup\$ – hobbs Jun 11 '16 at 20:49
  • 1
    \$\begingroup\$ @Timtech While I agree with you, community consensus is defined as Mego says. \$\endgroup\$ – Conor O'Brien Jul 27 '16 at 20:20
8
\$\begingroup\$

Julia, 28 27 21 bytes

n->sum(1./gamma(1:n))

This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable.

The approach is quite straightforward. We sum 1 divided by the gamma function evaluated at each of 1 through n. This takes advantage of the property n! = Γ(n+1).

Try it online!

Saved 1 byte thanks to Dennis and 6 thanks to Glen O!

\$\endgroup\$
  • \$\begingroup\$ Almost exactly the same in MATLAB: @(n)sum(1./factorial(0:n)) \$\endgroup\$ – flawr Jun 10 '16 at 23:47
5
\$\begingroup\$

Python, 36 bytes

Python 2:

f=lambda n,i=1:n/i and 1.+f(n,i+1)/i

Python 3:

f=lambda n,i=1:i<=n and 1+f(n,i+1)/i
\$\endgroup\$
  • \$\begingroup\$ Python 3 variant could be shorter with or instead of and: f=lambda n,i=1:i>=n or 1+f(n,i+1)/i. \$\endgroup\$ – Constructor Feb 14 '18 at 15:24
4
\$\begingroup\$

J, 10 bytes

[:+/%@!@i.

Straight-forward approach.

Explanation

[:+/%@!@i.    Input: n
        i.    Creates the range [0, 1, ..., n-1]
      !@      Maps factorial to each
    %@        Map 1/x to each
[:+/          Take the sum of the values and return it
\$\endgroup\$
4
\$\begingroup\$

CJam, 11

r~,:m!Wf#:+

or

r~{m!W#}%:+

Try it online: first version and second version

Explanation:

r~ = read and evaluate
m! = factorial
W# = raise to the -1 power (W = -1)
:+ = sum of array
First version constructs the [0…N-1] array and applies factorial and inverse to all its elements; 2nd version does factorial and inverse for each number then puts them in an array.

\$\endgroup\$
4
\$\begingroup\$

JavaScript ES6, 44 42 40

n=>{for(k=s=m=1;m<n;s+=k/=m++);return s}

An unnamed function now.

Thanks for saving 2 bytes @AlexA and thanks to @LeakyNun for another 2 bytes!

\$\endgroup\$
  • \$\begingroup\$ n=>{for(k=s=m=1;m<n;s+=k/=m++);return s} \$\endgroup\$ – Leaky Nun Jun 11 '16 at 4:12
4
\$\begingroup\$

MATL, 11 7 bytes

:Ygl_^s

4 bytes saved thanks to @Luis's recommendation to use gamma (Yg)

Try it Online

Explanation

        % Implicitly grab input (N)
:       % Create an array from 1...N
Yg      % Compute factorial(x-1) for each element (x) in the array
l_^     % Take the inverse
s       % Sum all elements
        % Implicitly display the result
\$\endgroup\$
  • \$\begingroup\$ You can remove ] \$\endgroup\$ – Luis Mendo Jun 11 '16 at 12:29
  • \$\begingroup\$ Also, 1i:Yg/s for 7 bytes \$\endgroup\$ – Luis Mendo Jun 11 '16 at 12:45
  • \$\begingroup\$ @LuisMendo oh yea I was hoping there was a better way to get a factorial but I had forgotten about gamma. Will update shortly \$\endgroup\$ – Suever Jun 11 '16 at 13:00
4
\$\begingroup\$

MATL, 6 bytes

q_t1Zh

This computes the sum using the hypergeometric function 1F1(a;b;z):

enter image description here

Works on Octave and on the online compiler, but not on Matlab, due to a difference in how the hypergeometric function is defined (which will be corrected).

Try it online!

Explanation

q_    % Take N implicitly. Compute -N+1
t     % Duplicate
1     % Push 1
Zh    % Hypergeometric function 1F1(-N+1;-N+1;1). Implicitly display
\$\endgroup\$
4
\$\begingroup\$

C, 249 bytes

#include <stdio.h>
#include <stdlib.h>
#define z double
z f(z x){z r=1;z n=1;while(x>0){r*=n;n++;x--;}return r;}int main(int argc, char **argv){z e=0;z p=0;z d=0;p=strtod(argv[1],NULL);while(p>0){e+=1.0d/f(d);printf("%.10f\n",e);p--;d++;}return 0;}

Ungolfed:

/* approximate e */

#include <stdio.h>
#include <stdlib.h>

double fact(double x){
    double result = 1;
    double num = 1;

    while (x > 0){
        result *= num;
        num++;
        x--;
    }
    return result;
}

int main(int argc, char **argv){
    double e = 0;
    double precision = 0;
    double denom = 0;

    precision = strtod(argv[1], NULL);
    while (precision > 0){
        e += 1.0d / fact(denom);
        printf("%.10f\n", e);
        precision--;
        denom++;
    }
    return 0;
}

Takes a number as an argument to determine number of iterations.

\$\endgroup\$
  • \$\begingroup\$ Hello, and welcome to PPCG! Great first post! \$\endgroup\$ – NoOneIsHere Jun 12 '16 at 18:42
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! I think the program is meant to print only the last approximation. At least with GCC, you don't need the int before main and the return 0. Also, if you replace NULL with 0, you don't need the includes. argc and argv can be shortened to single-letter variables. If you enjoy golfing in C, you might find Tips for golfing in C helpful. \$\endgroup\$ – Dennis Jun 12 '16 at 18:44
  • \$\begingroup\$ IMHO, even if the compiler throws some warnings but returns the correct result nevertheless, you can throw away many parts of your code to the point that nothing could be reduced without an error. \$\endgroup\$ – Andreï Kostyrka Jul 27 '16 at 19:26
  • \$\begingroup\$ And you don't need #include <stdio.h> \$\endgroup\$ – Leaky Nun Jul 28 '16 at 3:21
4
\$\begingroup\$

dc, 43 bytes

[d1-d1<f*]sf[dlfx1r/r1-d1<e+]se1?dk1-d1<e+p

This is a fairly direct translation of the series. I tried to be cleverer, but that resulted in longer code.

Explanation

[d1-d1<f*]sf

A simple factorial function, for n>0

[dlfx1r/r1-d1<e+]se

Execute the factorial for n,...,1; invert and sum

1?dk1-

Prime the stack with 1; accept input and set an appropriate precision

d1<e+

If input was 0 or 1, we can just pass it on, else compute the partial sum.

p

Print the result.

Test results

The first 100 expansions:

0
1
2
2.500
2.6666
2.70832
2.716665
2.7180553
2.71825394
2.718278766
2.7182815251
2.71828180110
2.718281826194
2.7182818282857
2.71828182844671
2.718281828458223
2.7182818284589936
2.71828182845904216
2.718281828459045062
2.7182818284590452257
2.71828182845904523484
2.718281828459045235331
2.7182818284590452353584
2.71828182845904523536012
2.718281828459045235360273
2.7182818284590452353602862
2.71828182845904523536028736
2.718281828459045235360287457
2.7182818284590452353602874700
2.71828182845904523536028747123
2.718281828459045235360287471339
2.7182818284590452353602874713514
2.71828182845904523536028747135253
2.718281828459045235360287471352649
2.7182818284590452353602874713526606
2.71828182845904523536028747135266232
2.718281828459045235360287471352662481
2.7182818284590452353602874713526624964
2.71828182845904523536028747135266249759
2.718281828459045235360287471352662497738
2.7182818284590452353602874713526624977552
2.71828182845904523536028747135266249775705
2.718281828459045235360287471352662497757231
2.7182818284590452353602874713526624977572453
2.71828182845904523536028747135266249775724691
2.718281828459045235360287471352662497757247074
2.7182818284590452353602874713526624977572470919
2.71828182845904523536028747135266249775724709352
2.718281828459045235360287471352662497757247093683
2.7182818284590452353602874713526624977572470936984
2.71828182845904523536028747135266249775724709369978
2.718281828459045235360287471352662497757247093699940
2.7182818284590452353602874713526624977572470936999574
2.71828182845904523536028747135266249775724709369995936
2.718281828459045235360287471352662497757247093699959554
2.7182818284590452353602874713526624977572470936999595729
2.71828182845904523536028747135266249775724709369995957475
2.718281828459045235360287471352662497757247093699959574944
2.7182818284590452353602874713526624977572470936999595749646
2.71828182845904523536028747135266249775724709369995957496673
2.718281828459045235360287471352662497757247093699959574966943
2.7182818284590452353602874713526624977572470936999595749669652
2.71828182845904523536028747135266249775724709369995957496696740
2.718281828459045235360287471352662497757247093699959574966967601
2.7182818284590452353602874713526624977572470936999595749669676254
2.71828182845904523536028747135266249775724709369995957496696762747
2.718281828459045235360287471352662497757247093699959574966967627699
2.7182818284590452353602874713526624977572470936999595749669676277220
2.71828182845904523536028747135266249775724709369995957496696762772386
2.718281828459045235360287471352662497757247093699959574966967627724050
2.7182818284590452353602874713526624977572470936999595749669676277240739
2.71828182845904523536028747135266249775724709369995957496696762772407632
2.718281828459045235360287471352662497757247093699959574966967627724076601
2.7182818284590452353602874713526624977572470936999595749669676277240766277
2.71828182845904523536028747135266249775724709369995957496696762772407663006
2.718281828459045235360287471352662497757247093699959574966967627724076630325
2.7182818284590452353602874713526624977572470936999595749669676277240766303508
2.71828182845904523536028747135266249775724709369995957496696762772407663035328
2.718281828459045235360287471352662497757247093699959574966967627724076630353518
2.7182818284590452353602874713526624977572470936999595749669676277240766303535449
2.71828182845904523536028747135266249775724709369995957496696762772407663035354729
2.718281828459045235360287471352662497757247093699959574966967627724076630353547565
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475915
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759429
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594542
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945681
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457111
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571352
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713792
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138185
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382143
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821752
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217826
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178492
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785218
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852481
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525131
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251635
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516607
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166394

Using 1000 terms:

2.7182818284590452353602874713526624977572470936999595749669676277240\
766303535475945713821785251664274274663919320030599218174135966290435\
729003342952605956307381323286279434907632338298807531952510190115738\
341879307021540891499348841675092447614606680822648001684774118537423\
454424371075390777449920695517027618386062613313845830007520449338265\
602976067371132007093287091274437470472306969772093101416928368190255\
151086574637721112523897844250569536967707854499699679468644549059879\
316368892300987931277361782154249992295763514822082698951936680331825\
288693984964651058209392398294887933203625094431173012381970684161403\
970198376793206832823764648042953118023287825098194558153017567173613\
320698112509961818815930416903515988885193458072738667385894228792284\
998920868058257492796104841984443634632449684875602336248270419786232\
090021609902353043699418491463140934317381436405462531520961836908887\
070167683964243781405927145635490613031072085103837505101157477041718\
986106873969655212671546889570350116
\$\endgroup\$
3
\$\begingroup\$

k (13 bytes)

Subject to overflows for N>20

{+/%*\1,1+!x}
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 6 bytes

$L<!/O

Explained

$           # push 1 and input: N = 5
 L<         # range [0..N-1]: [0,1,2,3,4]
   !        # factorial over range [1,1,2,6,24]
    /       # divide 1/range: [1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
     O      # sum: 2.708333333333333

Try it online

\$\endgroup\$
  • \$\begingroup\$ 5 bytes with L<!zO. \$\endgroup\$ – Grimy Sep 25 at 16:24
3
\$\begingroup\$

Pyke, 10 bytes

FSBQi^R/)s

Try it here!

Or 8 bytes if power=1

FSB1R/)s

Try it here!

\$\endgroup\$
  • \$\begingroup\$ the first code was off by more than 3 when I ran it: 5.436532738095238 \$\endgroup\$ – tox123 Jun 11 '16 at 21:10
  • \$\begingroup\$ @tox123 fixed now \$\endgroup\$ – Blue Jun 11 '16 at 21:16
  • \$\begingroup\$ are you testing these? I got: 7.3887125220458545 for the first, the second works much better. \$\endgroup\$ – tox123 Jun 11 '16 at 21:18
  • \$\begingroup\$ That one is an e^x one you know not just e \$\endgroup\$ – Blue Jun 11 '16 at 21:19
  • \$\begingroup\$ that's not the challenge. \$\endgroup\$ – tox123 Jun 11 '16 at 21:22
3
\$\begingroup\$

JavaScript (ES6), 28 bytes

f=(n,i=1)=>n&&1+f(n-1,i+1)/i
\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 6 bytes

+/÷!⍳⎕

+/ sum of
÷ the reciprocals of
! the factorials of
the numbers from 0 to
numerical input

Assumes ⎕IO←0, which is default on many systems.

TryAPL!

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

Haskell, 37 bytes

((scanl(+)0$(1/)<$>scanl(*)1[1..])!!)

Not the shortest, but arguably the prettiest.


Also courtesy of Laikoni, here is a solution that is 2 bytes shorter:

sum.(`take`((1/)<$>scanl(*)1[1..]))

λ> let f = ((scanl (+) 0 $ (1/) <$> scanl (*) 1 [1..]) !!)

λ> map f [1..5]
[1.0,2.0,2.5,2.6666666666666665,2.708333333333333]

λ> f 10
2.7182815255731922

λ> f 100
2.7182818284590455

λ> log (f 10)
0.9999998885745155

λ> log (f 100)
1.0
\$\endgroup\$
  • 2
    \$\begingroup\$ You can use this UTF-8 byte counter. I put in a suggested edit to add your byte count, which is 50. To add a header, use: ## Language, <xxx> bytes. \$\endgroup\$ – NoOneIsHere Jun 12 '16 at 15:12
  • 1
    \$\begingroup\$ Do you need the whitespace? \$\endgroup\$ – NoOneIsHere Jun 12 '16 at 15:13
  • 1
    \$\begingroup\$ You cannot assume the input to be present in a variable, so you need to prepend f n= or \n-> to get a valid function submission. However, we can also save a few bytes: (\x->1/x) can be shortened to the section (1/), [1,2..] is the same as [1..] and map(...)$ can be (...)<$>. Together 36 bytes: Try it online! \$\endgroup\$ – Laikoni Jun 30 '18 at 22:53
  • 1
    \$\begingroup\$ Converting to a point-free function saves another byte: Try it online! And even though it's a byte longer, ((scanl(+)0$(1/)<$>scanl(*)1[1..])!!) looks nice as well. \$\endgroup\$ – Laikoni Jul 1 '18 at 19:02
  • 1
    \$\begingroup\$ As you have seen yourself the version without parentheses is only a valid Haskell expression when inserting a value after it, but as assuming the input to be present in a predefined variable is not allowed, you have to add the parentheses or again a leading \n-> to create a function. \$\endgroup\$ – Laikoni Jul 9 '18 at 21:27
2
\$\begingroup\$

Actually, 6 bytes

r♂!♂ìΣ

Try it online!

Explanation:

r♂!♂ìΣ
r       range(N) ([0, N-1])
 ♂!     factorial of each element
   ♂ì   reciprocal of each element
     Σ  sum
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 18 bytes

:1-:0r:ef:$!a:/a+.

Explanation

:1-                 Subtract 1 from Input
   :0r              Create the list [0, Input - 1]
      :ef           Find all integers between 0 and Input - 1
         :$!a       Apply factorial to each member of that list
             :/a    Apply inverse to each element of that list
                +.  Unify the output with the sum of the list
\$\endgroup\$
2
\$\begingroup\$

C, 69 bytes

double f(int n){double s=1,f=1;for(int i=0;i++<n;s+=f)f/=i;return s;}

Ideone it!

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

Java with Ten Foot Laser Pole, 238 236 bytes

import sj224.tflp.math.*;interface U{static void main(String[]a){BigRational r=null,s,t;r=s=t=r.ONE;for(int n=new java.util.Scanner(System.in).nextInt()-1;n-->0;){t=t.multiply(r);s=s.add(t.pow(-1));r=r.add(r.ONE);}System.out.print(s);}}

Has much better overflow resistance than most of the other answers. For 100 terms, the result is

31710869445015912176908843526535027555643447320787267779096898248431156738548305814867560678144006224158425966541000436701189187481211772088720561290395499/11665776930493019085212404857033337561339496033047702683574120486902199999153739451117682997019564785781712240103402969781398151364608000000000000000000000
\$\endgroup\$
1
\$\begingroup\$

MATLAB / Octave, 22 bytes

@(x)sum(1./gamma(1:x))

Creates an anonymous function named ans that can be called using ans(N).

This solution computes gamma(x) for each element in the array [1 ... N] which is equal to factorial(x-1). We then take the inverse of each element and sum all elements.

Online Demo

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

Perl 5, 37 bytes

Not a winner, but nice and straightforward:

$e=$p=1;$e+=1/($p*=$_)for 1..<>;say$e

Outputs for inputs from 0 to 10:

1
2
2.5
2.66666666666667
2.70833333333333
2.71666666666667
2.71805555555556
2.71825396825397
2.71827876984127
2.71828152557319
2.71828180114638
\$\endgroup\$
1
\$\begingroup\$

R, 17 bytes

sum(1/gamma(1:n))

Quite straightforward, although numerical precision issues are bound to arise at some point in time.

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

Maple, 18

add(1/i!,i=0..n-1)

Usage:

> f:=n->add(1/i!,i=0..n-1);
> f(1);
  1
> f(4);
  8/3
\$\endgroup\$
1
\$\begingroup\$

WolframAlpha, 12 bytes

sum1/k!,0..n
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 44 bytes

n=>{for(a=d=i=1;i<=n;a+=1/d)d/=i++;return a}
\$\endgroup\$
0
\$\begingroup\$

F#, 87 bytes

let rec f x=if x<2 then 1 else f(x-1)*x
let e N=Seq.sumBy(fun x->1./float(f x)){0..N-1}

Try it online!

A direct implementation of the Maclaurin expansion. Unfortunately over 35 terms the denominator is too small, so the sum becomes infinity.

\$\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.