Python decimal.InvalidOperation Error Using A Large Number - python

In python, I wrote a program to work out the value of pi using the Chudnovsky Algorithm. It works on numbers under 800. However, if I use a number above 800, it returns a decimal.InvalidOperation error. This is my code:
from math import factorial
from decimal import Decimal, getcontext
getcontext().prec = 1000
pi_input = input("How Many Digits Of Pi Are To Be Represented: ")
num = int(pi_input)
def cal(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
for k in range(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
return round(pi, n)
print(cal(num))
Could Anyone Please Help Me?

I wouldn't recommend your method. Try using the gmpy module like this:
import sys
import math
import os.path
from gmpy2 import mpz, sqrt
from time import time, sleep
print_pi = input("Should The Value Of Pi Be Printed: ").lower()
print_pi_bool = 0
if "y" in print_pi:
print_pi_bool = True
elif "n" in print_pi:
print_pi = False
else:
print("Incorrect Input. Please Try Again.")
sys.exit()
def sqrt(n, one):
"""
Return the square root of n as a fixed point number with the one
passed in. It uses a second order Newton-Raphson convgence. This
doubles the number of significant figures on each iteration.
"""
# Use floating point arithmetic to make an initial guess
floating_point_precision = 10**16
n_float = float((n * floating_point_precision) // one) / floating_point_precision
x = (int(floating_point_precision * math.sqrt(n_float)) * one) // floating_point_precision
n_one = n * one
count = 0
while 1:
count += 1
print(count)
x_old = x
x = (x + n_one // x) // 2
if x == x_old:
break
return x
def pi_chudnovsky_bs(digits):
"""
Compute int(pi * 10**digits)
This is done using Chudnovsky's series with binary splitting
"""
C = 640320
C3_OVER_24 = C**3 // 24
def bs(a, b):
"""
Computes the terms for binary splitting the Chudnovsky infinite series
a(a) = +/- (13591409 + 545140134*a)
p(a) = (6*a-5)*(2*a-1)*(6*a-1)
b(a) = 1
q(a) = a*a*a*C3_OVER_24
returns P(a,b), Q(a,b) and T(a,b)
"""
if b - a == 1:
# Directly compute P(a,a+1), Q(a,a+1) and T(a,a+1)
if a == 0:
Pab = Qab = mpz(1)
else:
Pab = mpz((6*a-5)*(2*a-1)*(6*a-1))
Qab = mpz(a*a*a*C3_OVER_24)
Tab = Pab * (13591409 + 545140134*a) # a(a) * p(a)
if a & 1:
Tab = -Tab
else:
# Recursively compute P(a,b), Q(a,b) and T(a,b)
# m is the midpoint of a and b
m = (a + b) // 2
# Recursively calculate P(a,m), Q(a,m) and T(a,m)
Pam, Qam, Tam = bs(a, m)
# Recursively calculate P(m,b), Q(m,b) and T(m,b)
Pmb, Qmb, Tmb = bs(m, b)
# Now combine
Pab = Pam * Pmb
Qab = Qam * Qmb
Tab = Qmb * Tam + Pam * Tmb
return Pab, Qab, Tab
# how many terms to compute
DIGITS_PER_TERM = math.log10(C3_OVER_24/6/2/6)
N = int(digits/DIGITS_PER_TERM + 1)
# Calclate P(0,N) and Q(0,N)
P, Q, T = bs(0, N)
one_squared = mpz(10)**(2*digits)
sqrtC = sqrt(10005*one_squared, one_squared)
return (Q*426880*sqrtC) // T
# The last 5 digits or pi for various numbers of digits
check_digits = {
100 : 70679,
1000 : 1989,
10000 : 75678,
100000 : 24646,
1000000 : 58151,
10000000 : 55897,
}
if __name__ == "__main__":
digits = 100
pi = pi_chudnovsky_bs(digits)
#raise SystemExit
for log10_digits in range(1,11):
digits = 10**log10_digits
start =time()
pi = pi_chudnovsky_bs(digits)
pi = str(pi)
pi = pi[:(len(str(pi)) // 2) + 1]
length = int(len(str(pi))) - 1
print("Chudnovsky Binary Splitting Using GMPY: Digits",f"{digits:,}","\n--------------",time()-start,"--------------")
print("Length Of " + f"{length:,}" + " Digits")
It's my first answer, so I hope it helps!

Related

Is there a way to create a sign function in python?

import re
import math
from random
import randint
import hashlib
P = (-0.15, 2.645)
Q = (0.7, 2.71)
max_mod = 1.158 * 10 ** 77
def SHA256_INT(text):
return int(f'0x{hashlib.sha256(text.encode("ascii")).hexdigest()}', 0)
def ecc_double_slope(P):
slope = (3 * P[0] ** 2) / (2 * P[1])
return slope
def ecc_add(P, Q, slope):
xr = slope ** 2 - P[0] - Q[0]
yr = slope * (P[0] - xr) - P[1]
return (xr, yr)
def ecc_double(P):
slope = ecc_double_slope(P)
sum0 = ecc_add(P, P, slope)
return sum0
def ecc_double_for(P, limit):
lis = []
for i in range(limit):
b = ecc_double(P)
P = b
lis.append((2 ** i, b))
return lis
def greedy2(number):
x = 0
dub_lis = []
add_lis = []
while 2 ** x < number:
dub_lis.append(2 ** x)
x += 1
x -= 1
n = 2 ** x
while n != number:
y = x
while n + (2 ** y) > number:
y -= 1
n += (2 ** y)
x += 1
add_lis.append(2 ** y)
return len(dub_lis), add_lis
def ecc_main_add(P, Q):
x1 = P[0]
y1 = P[1]
x2 = Q[0]
y2 = Q[1]
slope = (y2 - y1) / (x2 - y1)
xr = slope ** 2 - x1 - x2
yr = slope * (x1 - xr) - y1
return xr, yr
def gen_points(gen, points):
if gen == 1:
return points
elif gen > 1:
if type(points) == int:
point_curve = (points, math.sqrt(points ** 3 + 7))
elif type(points) == tuple:
point_curve = points
point_steps = greedy2(gen)
point_dub = point_steps[0]
point_add = point_steps[1]
dub_list = ecc_double_for(point_curve, point_dub)
for i in point_add:
b = ecc_main_add(dub_list[int(math.log(i, 2))][1], dub_list[-1][1])
return b, gen
elif gen == 0:
return 0
def sign(messsage, private_key, public_key, G):
global max_mod
msg_hash = SHA256_INT(messsage)
randnum = randint(2, max_mod)
r = gen_points(randnum, G)[0]
r_x = r[0]
msg_hash = SHA256_INT(messsage)
s = (r_x * private_key + msg_hash) / randnum
p1 = gen_points(msg_hash/s, G)
p2 = gen_points(r_x/s, public_key)
p3 = ecc_main_add(p1, p2)
return p3
pub, priv = gen_points(9756, P)
print(sign('hello', priv, pub, P))
Hello, I'm trying to implement a way to sign messages using this tutorial:
https://learnmeabitcoin.com/beginners/digital_signatures_signing_verifying
I've tried to follow the tutorial before, but it's either my key generation is wrong, I didn't follow the tutorial correctly, or both.
My current code generates an error, I've already debugged it and it generates the error: TypeError: 'NoneType' object is not subscriptable.
Does anyone know how to solve this?

Converting floats in Python to Scientific Numbers

So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:
r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')
print('_____________________')
v = float(input('Volume = '))
v_unit = input('Unit = ')
print('_____________________')
n = float(input('Moles = '))
print('_____________________')
t = float(input('Temperature = '))
t_unit = input('Unit = ')
# Unit Conversion
if p_unit == 'bar':
p = p * 0.987
if v_unit == 'cm3':
v = v / 1000
if v_unit == 'm3':
v = v * 1000
if t_unit == 'c':
t = t + 273
if t_unit == 'f':
t = ((t - 32) * (5 / 9)) + 273
# Solve Equation
def calc():
if p == 000:
return (n * r * t) / v
if v == 000:
return (n * r * t) / p
if n == 000:
return (p * v) / (r * t)
if t == 000:
return (p * v) / (n * r)
and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:
def conv_to_sci(num):
i = 0
if num > 10:
while num > 10:
num / 10
i = i - 1
if num < 10:
while num < 10:
num * 10
i = i + 1
return num + "x 10^" + i
but it didn't work. Any questions?
I'd just use numpy to get scientific notation
import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'
Use str.format
"{:.0e}".format(0.005)
This will print:
'5e-03'
Or,
def conv_to_sci(num):
i = 0
while int(num) != num:
num *= 10
i += 1
return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)
Will give: '5 x 10^3'

Chrome T-Rex-Game Reinforcement learning showing no improvement

I would like to create an AI for the Chrome-No-Internet-Dino-Game. Therefore I adapted this Github-Repository to fit my needs. I used the following formula to calculate the new Q:
Source: https://en.wikipedia.org/wiki/Q-learning
My problem now is that even after ~ 2.000.000 iterations my game score is not increasing.
You can find the game file here: https://pastebin.com/XrwQ0suJ
QLearning.py:
import pickle
import Game_headless
import Game
import numpy as np
from collections import defaultdict
rewardAlive = 1
rewardKill = -10000
alpha = 0.2 # Learningrate
gamma = 0.9 # Discount
Q = defaultdict(lambda: [0, 0, 0]) # 0 = Jump / 1 = Duck / 2 = Do Nothing
oldState = None
oldAction = None
gameCounter = 0
gameScores = []
def paramsToState(params):
cactus1X = round(params["cactus1X"] / 10) * 10
cactus2X = round(params["cactus2X"] / 10) * 10
cactus1Height = params["cactus1Height"]
cactus2Height = params["cactus2Height"]
pteraX = round(params["pteraX"] / 10) * 10
pteraY = params["pteraY"]
playerY = round(params["playerY"] / 10) * 10
gamespeed = params["gamespeed"]
return str(cactus1X) + "_" + str(cactus2X) + "_" + str(cactus1Height) + "_" + \
str(cactus2Height) + "_" + str(pteraX) + "_" + str(pteraY) + "_" + \
str(playerY) + "_" + str(gamespeed)
def shouldEmulateKeyPress(params): # 0 = Jump / 1 = Duck / 2 = Do Nothing
global oldState
global oldAction
state = paramsToState(params)
oldState = state
estReward = Q[state]
action = estReward.index(max(estReward))
if oldAction is None:
oldAction = action
return action
# Previous action was successful
# -> Update Q
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * (rewardAlive + gamma * max(estReward))
Q[oldState] = prevReward
oldAction = action
return action
def onGameOver(score):
# Previous action was NOT successful
# -> Update Q
global oldState
global oldAction
global gameCounter
global gameScores
gameScores.append(score)
if gameCounter % 10000 == 0:
print(f"{gameCounter} : {np.mean(gameScores[-100:])}")
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * rewardKill
Q[oldState] = prevReward
oldState = None
oldAction = None
if gameCounter % 10000 == 0:
with open("Q\\" + str(gameCounter) + ".pickle", "wb") as file:
pickle.dump(dict(Q), file)
gameCounter += 1
Game_headless.main(shouldEmulateKeyPress, onGameOver)
On every frame the gameplay() function from Game_headless.py calls shouldEmulateKeyPress(). Said function then returns 0 for Jump, 1 for duck and 2 for nothing.
I tried adjusting the constants, but that didn't show any effect.
If you any questions, please don't hesitate to ask me!
Thank you in advance!
Someone on Reddit did this, did you take a look at their code? https://www.reddit.com/r/MachineLearning/comments/8iujuu/p_tfrex_ai_learns_to_play_google_chromes_dinosaur/
I was able to fix the problem, but I don't really know what the mistake was. I added a return statement at the end the gameplay function, and somehow it works now.

Turning my Euler function in to a higher order Runge–Kutta (RK4) that runs with an O(h^4) algorithm?

I currently have the below as my Euler function but i would like to try this same function using the Runge-Kutta method as i believe it is more accurate
def Euler(U,V,n,dt):
images = []
for i in range(n):
Uc = U[1:-1, 1:-1]
Vc = V[1:-1, 1:-1]
U[1:-1, 1:-1]=Uc + dt * (Du * laplace(U,hx,ht) + F(Uc,Vc))
V[1:-1, 1:-1]=Vc + dt * (Dv * laplace(V,hx,ht) + G(Uc,Vc))
U=periodic(U)
V=periodic(V)
if i % 500 == 0:
images.append(V)
return images
I have tried to do this below however i can't get this to run at all
def RK4_2_d(U,V,t,c):
for k in range(len(t)-1):
uu=np.zeros((U.shape[0],V.shape[0]))
K1=ht*c*laplace(U[k,:,:],hx,hy);uu[1:-1,1:-1]=K1
K2=ht*c*laplace(U[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K2
K3=ht*c*laplace([U[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K3
K4=ht*c*laplace(U[k,:,:]+uu,hx,hy)
K1=ht*c*laplace(V[k,:,:],hx,hy);uu[1:-1,1:-1]=K1
K2=ht*c*laplace(V[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K2
K3=ht*c*laplace(V[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K3
K4=ht*c*laplace(V[k,:,:]+uu,hx,hy)
U[1:-1, 1:-1]=Uc + dt * (Du * laplace(U,hx,ht) + F(Uc,Vc))
V[1:-1, 1:-1]=Vc + dt * (Dv * laplace(V,hx,ht) + G(Uc,Vc))
U=periodic(U)
V=periodic(V)
if i % 500 == 0:
images.append(V)
return images
Am i going the right way about this?

Using scipy.integrate.ode to solve protoplanetary hydrostatic equilibria

I have written code to solve the protoplanetary hydrostatic equilibria equations using first order euler method, and the results are as expected. I now want to rewrite it using fourth order Runge-Kutta solution, which is builtin to scipy.integrate.ode
Expected result, attained by using a custom written euler method:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
universalGasConstant = 8.31
gravitationalConstant = 6.67 * 10**-11
astronomicalUnit = 1.5 * (10**11)
coreMass = 5.9 * 10**24
sunMass = 2 * (10**30)
coreRadius = 0
coreDensity = 5500.0
semiMajorAxis = 5 * astronomicalUnit
gasMeanMolecularMass = 2.3 * 10**-3
coreRadius = (coreMass / ((4 / 3) * np.pi * coreDensity))**(1 / 3)
print('coreradius is', coreRadius)
hillSphere = (1**-4)*(semiMajorAxis) * (((coreMass) / (3 * sunMass))**(1 / 3))
print('hillsphere is', hillSphere)#THIS IS THE HILLSPHERE
numberOfSlices = 100000000 #NUMBER OF SLICES
deltaRadius = hillSphere / numberOfSlices
print('slice length is', deltaRadius)
#gravitationalForce = ((gravitationalConstant * coreMass) /
#(coreRadius + (deltaRadius)))
sunSurfaceTemperature = 5800
sunRadius = 6.96 * 10**8
equilibriumTemperature = sunSurfaceTemperature * \
(sunRadius / (2 * semiMajorAxis))**(1 / 2)
print('equilibrium temperature at', semiMajorAxis,
'metres is', equilibriumTemperature, 'kelvin')
pressureAtRadius = 0
initialDensity = 10.0 #INITIAL DENSITY
densityAtRadius = 0
muOverRT = gasMeanMolecularMass/(equilibriumTemperature * universalGasConstant)
print('muOverRT is', muOverRT)
totalMass = coreMass
densityAtRadius = initialDensity
def function(y, r):
totalMass = y[0]
distanceFromCOG = y[1]
# the differential equations
dRhodr = -(((gravitationalConstant*totalMass*
densityAtRadius*muOverRT))/(distanceFromCOG**2))
dMdr = 4*np.pi*gravitationalConstant*densityAtRadius
#dPdr = (1/(muOverRT))*dRhodr
return [dRhodr, dMdr]
distanceFromCOG = coreRadius+np.linspace(0,numberOfSlices) #number of points
initialDensity = [0,0]
solution = ode(function,initialDensity,distanceFromCOG).set_integrator('vode', method = 'dopri5')
plt.plot(solution)
solution.set_integrator('dopri5')

Categories

Resources