L
L
lukepker2020-06-02 03:58:16
Python
lukepker, 2020-06-02 03:58:16

How to speed up the program?

I am writing a program for the laboratory work to find the digits of pi. Wrote the following code.

import time
start_time = time.time()

digits = 10000
result_pi = []
length = digits * 10 // 3
list_for_finding = []
denominators = [0]
false_nums = 0

i = 0
while i < length:
    list_for_finding.append(2)
    if i != 0 and i != length:
        denominators.append(i * 2 + 1)
    i += 1

digit = 0
while digit < digits:
    print(digit)
    print('{}/{}'.format(digit, digits))
    perenos = 0
    i = length - 1
    while i > 0:
        dec = list_for_finding[i] * 10
        sum = dec + perenos
        list_for_finding[i] = sum % denominators[i]
        perenos = sum // denominators[i] * i
        i -= 1

    dec = list_for_finding[0] * 10
    sum = dec + perenos
    list_for_finding[0] = sum % 10
    pi_for_append = sum // 10

    if pi_for_append < 9:
        false_nums = 1
        result_pi.append(pi_for_append)
    elif pi_for_append == 9:
        false_nums += 1
        result_pi.append(pi_for_append)
    else:
        i = len(result_pi) - 1
        while false_nums != 0:
            if result_pi[i] == 9:
                result_pi[i] = 0
            else:
                result_pi[i] += 1
            false_nums -= 1
            i -= 1
        false_nums = 1
        result_pi.append(0)
    digit += 1

i = 0
while i < len(result_pi):
    result_pi[i] = str(result_pi[i])
    i += 1
result_pi[0] += '.'
print(''.join(result_pi))
print(time.time() - start_time)

It works, but when searching, say, 10,000 characters, it takes about 5 minutes, while the 4GHz processor and 16GB of RAM are almost not loaded. Tell me, please, can I somehow allow pycharm (I write in it) to use more computer resources?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-06-02
@lukepker

PyPy

V
Vladimir Kuts, 2020-06-02
@fox_12

Do you need to output each iteration to the console?
Replace:

...
while digit < digits:
    print(digit)
    print('{}/{}'.format(digit, digits))
...

on the
...
while digit < digits:
    if not digit % 1000:
         print('{}/{}'.format(digit, digits))
...

Save some time already

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question