From 221be8caf49fdd37e0013c80d2df85f8b725860b Mon Sep 17 00:00:00 2001 From: Mark Piper Date: Wed, 19 Jul 2023 13:27:25 -0600 Subject: [PATCH] Add Python script example --- lessons/hpc/calculate_pi.py | 27 +++++++++++++++++++++++++++ lessons/hpc/calculate_pi.sh | 19 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 lessons/hpc/calculate_pi.py create mode 100644 lessons/hpc/calculate_pi.sh diff --git a/lessons/hpc/calculate_pi.py b/lessons/hpc/calculate_pi.py new file mode 100644 index 0000000..6d03b50 --- /dev/null +++ b/lessons/hpc/calculate_pi.py @@ -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)) diff --git a/lessons/hpc/calculate_pi.sh b/lessons/hpc/calculate_pi.sh new file mode 100644 index 0000000..cfd91cc --- /dev/null +++ b/lessons/hpc/calculate_pi.sh @@ -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`