Esempio n. 1
0
def PI(maxK=70,
       prec=1008,
       disp=1007,
       K=6,
       M=1,
       L=13591409,
       X=1,
       S=13591409,
       ki=1):
    gc().prec = prec
    '''
    state = getState(maxK, prec, disp)
    if state != None:
        K,M,L,X,S,ki = int(state['K']),int(state['M']),int(state['L']),int(state['X']),Dec(state['S']),int(state['k'])
    '''

    for k in range(ki, maxK + 1):
        M = (K**3 - 16 * K) * M // k**3
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
        #saveState(K,M,L,X,S,k,maxK,prec,disp)
        print(f'k:{k}', flush=True)

    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])
    print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format(
        maxK, prec, disp, pi))
    return pi
def chudnovsky(precision, max_iter=100, timeout=False):
    """
    
    Calculates pi using the Chudnovsky algorithm:
    https://en.wikipedia.org/wiki/Chudnovsky_algorithm

    Runs in O(n log(n)^3).
    
    :param precision: The level of precision to be used
    :param max_iter: The maximum number of iterations to be used
    :param timeout: The maximum number of seconds to pass before refusing to continue summation.
    Note that this can potentially drastically affect the accuracy of the calculation.
    :return: Pi to some level of precision
    """
    gc().prec = precision + 1
    k_term = 6
    multinomial_term = 1
    linear_term = 13591409
    exponential_term = 1
    current_sum = 13591409
    start = time.time()
    for k in range(1, max_iter + 1):
        if timeout and time.time() > start + timeout:
            break
        multinomial_term = (k_term**3 - 16 * k_term) * multinomial_term // k**3
        linear_term += 545140134
        exponential_term *= -262537412640768000
        current_sum += Dec(multinomial_term * linear_term) / exponential_term
        k_term += 12
    c_term = 426880 * Dec(10005).sqrt()
    pi = c_term / current_sum
    pi = Dec(str(pi)[:precision])  # Only return up to the level of precision
    return pi
Esempio n. 3
0
def Chudnovsky(n):
    gc().prec = n

    if n > 1000:
        raise Exception(
            f"User entered [{n}]: out of bounds exception.\nValue must be <=1000."
        )

    #initialize
    _sum = 0
    C = Dec(426880) * Dec(10005).sqrt()
    M, L, X = Dec(1), Dec(13591409), Dec(1)
    _sum += Dec(M * L) / Dec(X)

    #The number of iterations: the chudnovsky algorithm calculates ~14 decimal places per iteration
    #so to cut excess iterations we look at the number of desired decimal places
    k = n // 14

    #produce next summation terms
    for i in range(0, k):
        L += Dec(545140134)
        X *= Dec(-262537412640768000)
        M *= Dec((12 * i + 2) * (12 * i + 6) * (12 * i + 10) / ((i + 1)**3))
        _sum += Dec(M * L) / Dec(X)
    ans = C / _sum

    #determine error
    err = Dec(ans - pi)

    return [ans, err]
Esempio n. 4
0
def e_Calculator():

    print("'e' (Euler's number) Calculator")
    digits = int(
        input('Enter the number of digits you want for your value of e : '))
    steps = int(
        input(
            'Enter the maximum number of steps desired (if unsure, enter 500) : '
        ))
    prec = 3 * digits
    gc().prec = prec
    maxSteps = steps  # You should stop when k! > 10^n
    # See Gourdon & Sebah (2001) Mathematical constants and computation, Jan 11
    s = 1

    for k in range(1, maxSteps + 1):
        numerator = 1
        denominator = factorial(k)
        s += Dec(1) / factorial(
            k
        )  # Note, if you do Dec(1/factorial(k)), your answer will diverge after the 16th decimal place

    e = s
    e = Dec(str(e)[:digits + 1])  # Drop few digits of precision for accuracy
    print(f'Your value for e = {e}')
    print(
        '\nThe value obtained should not diverge from http://www.numberworld.org/digits/E/ or other reference value.'
    )
    print('But if it does, then you must increase the number of steps.')
    print(
        'However, increasing the number of digits or steps comes at the cost of processor power.'
    )
def calculate_e(precision, max_iter=100, timeout=False):
    """

    Calculates e using an algorithm found here:
    https://en.wikipedia.org/wiki/List_of_representations_of_e

    Accurate to within 2 * 10^-12 after 5 iterations.

    :param precision: The level of precision to be used
    :param max_iter: The maximum number of iterations to be used
    :param timeout: The maximum number of seconds to pass before refusing to continue summation.
    Note that this can potentially drastically affect the accuracy of the calculation.
    :return: Euler's number e to some level of precision
    """
    gc().prec = precision + 1
    current_sum = Dec(0)
    start = time.time()
    for k in range(0, max_iter + 1):
        if timeout and time.time() > start + timeout:
            break
        numerator = Dec((4 * k) + 3)
        denominator_left = Dec(2**((2 * k) + 1))
        denominator_right = factorial(Dec(2 * k + 1))
        current_term = Dec(numerator / (denominator_left * denominator_right))
        current_sum += current_term
    e = Dec(current_sum)**2
    e = Dec(str(e)[:precision])  # Only return up to the level of precision
    return e
Esempio n. 6
0
def machin_for():
    arc_tan_1_239 = arc_tan(1 / 239, 3)
    arc_tan_1_5 = arc_tan(1 / 5, 3)

    filename = os.path.abspath('../y-cruncher/10K/pi-dec-chudnovsky.txt')
    f = open(filename, "r")
    ref = f.read()

    number = 0

    for i in range(3, gc().prec):
        arc_tan_1_239 += arc_tan_it(1 / 239, i)
        arc_tan_1_5 += arc_tan_it(1 / 5, i)
        pi = 4 * (4 * arc_tan_1_5 - arc_tan_1_239)
        if (i % ((gc().prec) // 100) == 0):
            print('\n')
            print(str(pi)[:number])
            print(i)
            number = check(str(pi), ref, number, gc().prec)
            print(number)
    print(str(pi)[:number])
Esempio n. 7
0
def PI(maxK=70, prec=1008, disp=1007): # parameter defaults chosen to gain 1000+ digits within a few seconds
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409 
    for k in range(1, maxK+1):
        M = (K**3 - (K<<4)) * M / k**3 
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp]) # drop few digits of precision for accuracy
    print("PI(maxK=%d iterations, gc().prec=%d, disp=%d digits) =\n%s" % (maxK, prec, disp, pi))
    return pi
Esempio n. 8
0
def PI(maxK: int = 70, prec: int = 1008, disp: int = 1007):  # Parameter defaults chosen to gain 1000+ digits within a few seconds
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409
    start = time.time()
    for k in range(1, maxK + 1):
        M = (K**3 - 16*K) * M // k**3 
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])  # Drop few digits of precision for accuracy
    number=compare(str(pi),disp)
    end = time.time()
    elapsed = end - start
    print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}\n\ntime: {}\n\nnumber: {}".format(maxK, prec, disp, pi, elapsed, number))
    return pi
Esempio n. 9
0
def PI(
    maxK=317,
    prec=15001,
    disp=15000
):  # Parameter defaults chosen to gain 1000+ digits within a few seconds
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409
    for k in range(1, maxK + 1):
        M = (K**3 - 16 * K) * M // k**3
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])  # Drop few digits of precision for accuracy
    #print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format(maxK, prec, disp, pi))
    return pi
Esempio n. 10
0
def PI(
    maxK=70,
    prec=1008,
    disp=1007
):  # parameter defaults chosen to gain 1000+ digits within a few seconds
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409
    for k in range(1, maxK + 1):
        M = (K**3 - 16 * K) * M // k**3
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])  # drop few digits of precision for accuracy
    print("PI(maxK=%d iterations, gc().prec=%d, disp=%d digits) =\n%s" %
          (maxK, prec, disp, pi))
    return pi
Esempio n. 11
0
def pi(maxK=70, prec=1008, disp=1007):
    """
    maxK: nuber of iterations
    prec: precision of decimal places
    disp: number of decimal places shown
    """
    from decimal import Decimal as Dec, getcontext as gc
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409
    for k in range(1, maxK + 1):
        M = Dec((K**3 - (K << 4)) * M / k**3)
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])
    return pi
Esempio n. 12
0
def pi(maxK=70, prec=1008, disp=1007):
    """
    maxK: nuber of iterations
    prec: precision of decimal places
    disp: number of decimal places shown
    """
    from decimal import Decimal as Dec, getcontext as gc
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409 
    for k in range(1, maxK+1):
        M = Dec((K**3 - (K<<4)) * M / k**3)
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])
    return pi
Esempio n. 13
0
def pi_to_n(digits):

    X, M, K, L, S = 1, 1, 6, 13591409, 13591409
    C = Decimal(426880 * math.sqrt(10005))
    gc().prec = 1000

    for k in range(1, 70):

        M += M * (K**3 - 16 * K) / k**3
        K += 12
        X *= -262537412640768000
        L += 545140134
        S += Decimal(M * L) / X

    pi = C / S
    pi = Decimal(str(pi)[:digits + 2])

    print(pi)
    return pi
Esempio n. 14
0
def calcChud(
    maxIter=70,
    prec=1003,
    disp=1002
):  # parameter defaults chosen to gain 1000 digits after the comma
    gc().prec = prec
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409
    for k in range(1, maxIter + 1):
        M = (K**3 - 16 * K) * M // k**3
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:disp])  # drop few digits of precision for accuracy
    print(
        "PI(maxIter={} iterations, gc().prec={}, disp={} digits) =\n{}".format(
            maxIter, prec, disp, pi))
    return pi
Esempio n. 15
0
def PI2(K):
    global teclado
    global final
    p = 0
    gc().prec = 156
    start_time = time.time()
    contador = 0
    iteracion = 0
    for n in range(0, K + 1):
        while (teclado == True):
            if contador == 0:
                print("Pausado")
                contador = 1
            else:
                contador = 1
            #print("\n")
        A = (-1)**n
        B = factorial(6 * n)
        C = (545140134 * n + 13591409)
        D = (factorial(3 * n))
        E = (factorial(n)**3)
        F = Dec((640320))**Dec((3 * n + (3 / 2)))
        p = (((A * B * C) / (D * E * F)) + p)
        iteracion = 1 + iteracion
        porcentaje = (iteracion / K) * 100
        print(porcentaje)
    pi = 1 / (12 * p)
    pi = str(pi)[:154]
    guardar(pi)
    por = similar(
        pi,
        "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848"
    )
    print(
        "\nPID: %s, similitud con pi %s, Thread Name: %s, \nValor de pi: %s " %
        (os.getpid(), por, threading.current_thread().name, pi))
    final = final + 1

    end_time = time.time()
    print("El tiempo del thread =", end_time - start_time)
    return
Esempio n. 16
0
def nthOfPI(
    iteration=70,
    precision=110,
    display=100
):  # parameter defaults chosen to gain 100 digits within a short time
    gc().prec = precision
    K, M, L, X, S = 6, 1, 13591409, 1, 13591409  #the values defined here are part of constants of Chudnovsky Algorithm

    for k in range(1, iteration + 1):  #Algorithm Implemented

        M = (K**3 - 16 * K) * M // k**3
        L += 545140134
        X *= -262537412640768000
        S += Dec(M * L) / X
        K += 12
    pi = 426880 * Dec(10005).sqrt() / S
    pi = Dec(str(pi)[:display])  # drop few digits of precision for accuracy
    print(
        "PI(Loop={} iterations, context precision={}, display={} digits) =\n{}"
        .format(iteration, precision, display, pi))
    return pi
Esempio n. 17
0
import matplotlib.pyplot as plt
import numpy as np

### System Subroutine ###
clear = lambda: os.system('cls')
unicode_cmd = lambda: os.system('chcp 65001 &')

### System Variable Settings ###
"""
_V -> V; _Q -> Q; oVFE -> V'; _Q2 -> Q'; _tFE -> tFE; _EC -> EC; _Pr -> Pr
math.pow(10,4) -> 10X10X10X10
math.sqrt(4) -> √4
2*3 - > 2X3
"""
cfg_parameter = cfg.Config().get('parameter')
gc().prec = int(cfg_parameter['f_len'])  # set float precision
_tFE = eval(cfg_parameter['tfe'])
_Ec = eval(cfg_parameter['ec'])
_Pr = eval(cfg_parameter['pr'])

cfg_file = cfg.Config().get('file')  # set float precision
dirsrcpath = cfg_file['src']
if cfg_file['src'] is '':
    dirsrcpath = cfg.Config().path + 'src' + '\\'
dirdstpath = cfg_file['dst']
if cfg_file['dst'] is '':
    dirdstpath = cfg.Config().path + 'dst' + '\\'
if not os.path.exists(dirdstpath):
    os.makedirs('dst')
ofilename = cfg_file['src_f_org']  # orignal filename
mfilename = cfg_file['src_f_map']  # map v-i filename
Esempio n. 18
0
#!/usr/bin/env python -i

# Calculating radical form expression for cos(2^n * pi / 257)

from math import *
from decimal import Decimal as Dec, getcontext as gc
gc().prec = 30
s = lambda r: Dec(r).sqrt()

Q = lambda b, c: ((b + s(b * b - 4 * c)) / 2, (b - s(b * b - 4 * c)) / 2)

t0, t1 = Q(-1, -64)
t = [t0, t1]
(z0, z2), (z1, z3) = Q(t0, -16), Q(t1, -16)
z = [z0, z1, z2, z3]

Y = lambda z, t: Q(z, -5 - t - 2 * z)
(y0, y4), (y5, y1), (y2, y6), (y7, y3) = (Y(z0, t0), Y(z1,
                                                       t1), Y(z2,
                                                              t0), Y(z3, t1))
y = [y0, y1, y2, y3, y4, y5, y6, y7]

X = lambda n: Q(y[n], t[n & 1] + y[n] + y[(n + 2) & 7] + 2 * y[(n + 5) & 7])
(x0, x8), (x1, x9), (x2, x10), (x3, x11), (x4,
                                           x12), (x5,
                                                  x13), (x14,
                                                         x6), (x7, x15) = map(
                                                             X, range(8))
x = [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15]

V = lambda n: Q(x[n], x[n] + x[(n + 1) & 15] + x[(n + 2) & 15] + x[
Esempio n. 19
0
from decimal import Decimal as de
from decimal import getcontext as gc

gc().prec = 50

f = 1
e = de(2)

for i in range(2, 50):
    f *= i
    e += de(1)/de(f)
#    print(f)
    print(e)
Esempio n. 20
0
# Voir http://serge.mehl.free.fr/anx/pi_machin.html

import math
import time
import os

from decimal import Decimal as Dec, getcontext as gc
gc().prec = 100000


def arc_tan_it(x, n):
    '''
    Arctan nème terme
    '''
    numerator = math.pow(-1, n) * math.pow(x, 2 * n + 1)
    denominator = 2 * n + 1
    return Dec(numerator) / Dec(denominator)


def arc_tan(x, iterations):
    '''
    Arctan à l'ordre 'iterations' de 'x'
    '''
    arc_tan_of_x = Dec(0)
    for n in range(0, iterations):
        arc_tan_of_x += arc_tan_it(x, n)
    return arc_tan_of_x


def check(calculated, ref, number, prec):
    test = True