Computing e in Raku

How to compute the value of the mathematical constant e using recursion in the Raku programming language.

There is a simple formula to compute the value of the mathematical constant e:

It converges rather quickly, so even a few dozen of iterations is enough to get a good approximation.

The only thing to think about is not to calculate factorial inefficiently. So, I suggest to use the recursive factorial implementation which caches the already-calculated values. (Of course, you can write even more efficient program if you organise it with a couple of loops and variables.)

Having the factorial code ready, the whole program for computing e is a half-liner:

say [+] map 1 / *!, ^20;

The program prints 2.718281828459045.

Browse for the full program in the GitHub repository.

This post is my solution to the Task 1 of Week 21 of the Perl Weekly Challenge.

GitHub repository
Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *