Home > Blockchain >  Optimization of a simple Python script to calculate the first sophomore's dream number
Optimization of a simple Python script to calculate the first sophomore's dream number

Time:03-27

I am currently working on a program to calculate 100,000 digits of the first sophomore's dream constant, I1. It's given by the sum below.

enter image description here

After about 10,000 terms in this series it gets quite slow. I opted to write the program so small because I wanted to see how small I could make it

from decimal import *

def sophodream(a):
    s,i,t=0,1,int(a*1.5)
    while i<t:
         print(i)
         n,d=Decimal(pow(-1,i 1)),Decimal(i**i)
         f=n/d
         s =f
         i =1
    return s

I would like to know if there are any ways to speed this up aside from multithreading/multiprocessing. I find that when I do series like these in threaded pieces the accuracy of them gets lower.

CodePudding user response:

There are some minor changes / simplifications that can be made to your code but as has already been noted, you're working (at times) with some very big numbers.

from decimal import getcontext, Decimal

def sophodream(a):
    s, p = 0, 1
    getcontext().prec = a
    for i in range(1, int(a * 1.5)):
        s  = p / Decimal(i**i)
        p = -p
    return s

print(sophodream(100))

Output:

0.7834305107121344070592643865269754694076819901469309582554178227016001845891404456248642049722689389

Obviously just a very short version to prove functionality

  • Related