Skip to content

Commit

Permalink
Add Python script example
Browse files Browse the repository at this point in the history
  • Loading branch information
mdpiper committed Jul 19, 2023
1 parent f20200c commit 221be8c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lessons/hpc/calculate_pi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Approximate pi with the Bailey-Borwein-Plouffe formula.
Adapted from:
http://blog.recursiveprocess.com/2013/03/14/calculate-pi-with-python
"""

import sys
from decimal import Decimal


def bailey_borwein_plouffe_formula(n):
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(1) / (16**k)) * (
(Decimal(4) / (8 * k + 1))
- (Decimal(2) / (8 * k + 4))
- (Decimal(1) / (8 * k + 5))
- (Decimal(1) / (8 * k + 6))
)
k += 1
return pi


if __name__ == "__main__":
for i in range(1, int(sys.argv[1])):
print(i, bailey_borwein_plouffe_formula(i))
19 changes: 19 additions & 0 deletions lessons/hpc/calculate_pi.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
#SBATCH --job-name=calculate_pi
#SBATCH --output=%x_%j.out
#
# A job script that calls a Python script that approximates pi.
#
# Submit this script to the scheduler with:
# $ qsub calculate_pi.pbs.sh

module purge
module load anaconda/2022.10

hostname
python --version

echo "Calculating pi with the Bailey-Borwein-Plouffe formula"
echo "Start time:" `date`
python calculate_pi.py 20
echo "End time:" `date`

0 comments on commit 221be8c

Please sign in to comment.