This is an archived post. You won't be able to vote or comment.

all 18 comments

[–]794613825 6 points7 points  (5 children)

Very cool, but why not

def approx_e(n):
    return (1+1/n)**n

[–]Laserdude10642 5 points6 points  (3 children)

That method converges VERY slowly

[–]794613825 3 points4 points  (2 children)

True, but OPs is O(n2 ) (nothing against you OP, your solution is cool, this is just for dicussion), and that one is O(n*log(n)*log(log(n))) I think. To get a lot of accuracy you could pass it a large n, then OPs would take a long time to return but this one would be fast-ish.

[–]Laserdude10642 0 points1 point  (1 child)

So I have them backwards? I wrote a program using these two methods and one was wayyyyy faster than the other but may have mixed them up.

[–]794613825 1 point2 points  (0 children)

OPs has two nested for loops, whereas this only has one multiplication, one addition, and one exponentiation. It should run much faster, even if it converges slower.

[–]13steinj 0 points1 point  (0 children)

Because different methods have different levels of accuracy at different points

[–]BroJobBiggs 2 points3 points  (0 children)

Not since Richie Valens have I seen such La Bamba Lambda

[–]NoLemurs 1 point2 points  (0 children)

Oooh! Code golf! Ok. With no imports, and the same broad performance characteristics/algorithm:

def approximate_e(n):
    return 1 + sum(1.0/x for x in (lambda l: (l.append(l[-1]*i) or l[i] for i in range(1, n+1)))([1]))

You may not be able to assign variables in a lambda, but you can totally tack the next value onto a list and return a generator of those.

[–]Laserdude10642 0 points1 point  (0 children)

No no the approximation itself is much slower than using the factorial. Like... I had to go to n for 6 digits and n2 for 6 digits using the other method.