Code: Select all
from math import factorial
from decimal import Decimal, getcontext
from joblib import Parallel, delayed
from tqdm import trange
import time
def calc(n_digits):
# number of iterations
n = int(n_digits+1/14.181647462725477)
n = n if n >= 1 else 1
# set the number of digits for our numbers
getcontext().prec = n_digits+1
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
for k in trange(n):
t = ((-1)**k)*(factorial(6*k))*(13591409+545140134*k)
deno = factorial(3*k)*(factorial(k)**3)*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12) / Decimal(640320 ** Decimal(1.5))
pi = 1/pi
# no need to round
return pi
def parallel_with_joblib():
# Define the number of cores to use
n_cores = 4
# Define the tasks (e.g., compute first 100, 200, 300, 400 digits of pi)
tasks = [1200, 1700, 900, 1400]
# Run tasks in parallel
results = Parallel(n_jobs=n_cores)(delayed(calc)(n) for n in tasks)
if __name__ == "__main__":
parallel_with_joblib()
Folge der Methode von @Swifty und ändere die Anzahl der Kerne auf 3 und die Anzahl der Aufgaben auf 7 und ändere Leave=False in Leave=True. Ich habe diesen Code:
Code: Select all
from math import factorial
from decimal import Decimal, getcontext
from joblib import Parallel, delayed
from tqdm import trange
import time
def calc(n_digits, pos, total):
# number of iterations
n = int(n_digits + 1 / 14.181647462725477)
n = n if n >= 1 else 1
# set the number of digits for our numbers
getcontext().prec = n_digits + 1
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
for k in trange(n, position=pos, desc=f"Job {pos + 1} of {total}", leave=True):
t = ((-1) ** k) * (factorial(6 * k)) * (13591409 + 545140134 * k)
deno = factorial(3 * k) * (factorial(k) ** 3) * (640320 ** (3 * k))
pi += Decimal(t) / Decimal(deno)
pi = pi * Decimal(12) / Decimal(640320 ** Decimal(1.5))
pi = 1 / pi
# no need to round
return pi
def parallel_with_joblib():
# Define the number of cores to use
n_cores = 3
# Define the tasks (e.g., compute first 100, 200, 300, 400 digits of pi)
tasks = [1200, 1700, 900, 1400, 800, 600, 500]
# Run tasks in parallel
results = Parallel(n_jobs=n_cores)(delayed(calc)(n, pos, len(tasks)) for (pos, n) in enumerate(tasks))
if __name__ == "__main__":
parallel_with_joblib()
Das gibt mir jedoch Folgendes:

und dann entsteht am Ende noch mehr Chaos:

Wie kann das behoben werden?