Skip to content

Instantly share code, notes, and snippets.

@JJ
Last active January 6, 2017 11:29
Show Gist options
  • Save JJ/23801c82b218b25da7fc8831b7c331ad to your computer and use it in GitHub Desktop.
Save JJ/23801c82b218b25da7fc8831b7c331ad to your computer and use it in GitHub Desktop.
Cool perl6 one liners vol. 2: Computing Pi from a series
#You can also copy/paste this directly into the command line if perl6 is installed
perl6 -e "say π - 4 * ([+] (( 1 <</<< (1,5,9...5000) ) Z ( -1 <</<< (3,7...5000))).flat)"
# This is an implementation of the Madhava-Lebniz series: https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
# This script creates two series (1,5...) and (3,7) for even and odd positions in the sequence.
# Then, the inverse of the sequence is computed 1/(the sequence) with the 1<</<< construction
# Then they are zipped together using Z
# Finally, [+] sums all terms of the sequence together. Since the sequence is an approximation to π/4 it's multiplied by 4
# and then substracted from π. This should give a good 3-digit approximation. Change 5000 by a bigger number if you want bigger precision
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment