Implementation of binomial option pricing closed form expression - python

I am trying to implement this formula in python:
This is the code I think came up with:
N = 2
S0 = 10
K = 9
T = 2
r = 0.2
import math
def combos(n, i):
return math.factorial(n) / (math.factorial(n-i)*math.factorial(i))
def binom(S0, K , T, r, N, type_ = 'call'):
dt = T/N
# u = np.exp(sigma * np.sqrt(dt))
# d = np.exp(-sigma * np.sqrt(dt))
# p = ( np.exp(r*dt) - d ) / ( u - d )
u = 1.5
d = 0.5
p = 0.2
value = 0
for i in range(N+1):
node_prob = combos(N, i)*p**i*(1-p)**(N-i)
ST = S0*(u)**i*(d)**(N-i)
print(ST)
if type_ == 'call':
value += max(ST-K,0) * node_prob
elif type_ == 'put':
value += max(K-ST, 0) * node_prob
else:
raise ValueError("type_ must be 'call' or 'put'" )
return value*(1/(1+r)**T)
binom(S0, K, T, r, N)
But when I try to calculate the option price above I don't get 4.59375 but instead get 0.3750. As you can see i don't have to calculate the u,d and p as they are given. So it my code incorrect or is the example wrong?

Related

real gas, 1D pipe flow in Pyomo + SCIP failing through energy equation?

Hi there smart people!
I am trying to implement a 1D, steady-state, real gas (compressibility factor) pipe flow model in Python using Pyomo + SCIP. It basically amounts to solving a DAE system. The formulation is an adopted version from chapter 10 in Koch, T.; Hiller, B.; Pfetsch, M.E.; Schewe, L. Evaluating Gas Network Capacities; Series on Optimization, MOS-SIAM, 2015.
However, I am encountering several problems:
The problem seems to be numerically sensitive to a combination of the discretization step length and input parameters (mass flow, pipe length).
Does not solve for any other model but ideal gas.
With a suitable discretization, and an ideal gas law, I get a result that seems reasonable (see example). In all other cases it turns out to be infeasible.
I may be overlooking something here, but I do not see it. Therefore, if anyone is inclined to try and help me out here, I would be thankful.
The example below should produce a valid output.
Edit: I realized I had one false constraint in there belonging to another model. The energy equation works now. However, the problems mentioned above remain.
from pyomo.dae import *
from pyomo.environ import *
import matplotlib.pyplot as plt
from math import pi
from dataclasses import dataclass
#dataclass
class ShomateParameters:
A: float
B: float
C: float
D: float
E: float
def specific_isobaric_heat_capacity(self, temperature):
# in J/(mol*K)
return self.A + self.B * (temperature/1000) + self.C * (temperature/1000)**2 + self.D * (temperature/1000)**3 + self.E/(temperature/1000)**2
def plot(self, temperature_start, temperature_end, points_to_mark=None):
assert temperature_start <= temperature_end, "temperature_start <= temperature_end must hold."
temperatures = [i for i in range(temperature_start, temperature_end+1)]
values = [self.specific_isobaric_heat_capacity(temp) for temp in temperatures]
fig, ax = plt.subplots()
ax.plot(temperatures, values)
if points_to_mark is not None:
ax.scatter(points_to_mark, [self.specific_isobaric_heat_capacity(temp) for temp in points_to_mark])
ax.set(xlabel='temperature [K]', ylabel='specific isobaric heat capacity [J/(mol*K)]',
title='Shomate equation:\n A + B*T + C*T^2 + D*T^3 + E/T^2')
ax.grid()
plt.show()
#dataclass
class Species:
MOLAR_MASS: float # kg/mol
CRITICAL_TEMPERATURE: float # Kelvin
CRITICAL_PRESSURE: float # Pa
DYNAMIC_VISCOSITY: float # Pa*s
SHOMATE_PARAMETERS: ShomateParameters
METHANE = Species(MOLAR_MASS=0.016043,
CRITICAL_TEMPERATURE=190.56,
CRITICAL_PRESSURE=4599000,
DYNAMIC_VISCOSITY=1.0245e-5,
SHOMATE_PARAMETERS=ShomateParameters(
A=-0.703029,
B=108.4773,
C=-42.52157,
D=5.862788,
E=0.678565))
# select gas species
gas = METHANE
# select equation of state ('ideal', 'AGA' or 'Papay')
formula = 'ideal'
PIPE_LENGTH = 24000 # meter
start = 0 # meter
end = start + PIPE_LENGTH
MASS_FLOW = 350 # kg/s
PIPE_SLOPE = 0.0
PIPE_DIAMETER = 1.0 # meter
PIPE_INNER_ROUGHNESS = 6e-5 # 15e-6 # meter 6e-6 # meter
# gravitational acceleration
G = 9.81 # meter**2/s**2
# gas temperature at entry
TEMPERATURE = 283.15
# temperature ambient soil
TEMPERATURE_SOIL = 283.15 # Kelvin
# gas pressure at entry
PRESSURE = 4.2e6 # Pa
GAS_CONSTANT = 8.314 # J/(mol*K)
print(gas.SHOMATE_PARAMETERS)
print(gas.SHOMATE_PARAMETERS.specific_isobaric_heat_capacity(TEMPERATURE))
gas.SHOMATE_PARAMETERS.plot(273, 400, points_to_mark=[TEMPERATURE])
##################################################################################
# Variable bounds
##################################################################################
pressure_bounds = (0, 1e7) # Pa
temperature_bounds = (0, 650) # Kelvin
density_bounds = (0, 100)
idealMolarIsobaricHeatCapacityBounds = (0, 200)
correctionIdealMolarIsobaricHeatCapacityBounds = (-250, 250)
velocity_bounds = (0, 300)
##################################################################################
# Create model
##################################################################################
m = ConcreteModel()
##################################################################################
# Parameters
##################################################################################
m.criticalPressure = Param(initialize=gas.CRITICAL_PRESSURE)
m.criticalTemperature = Param(initialize=gas.CRITICAL_TEMPERATURE)
m.molarMass = Param(initialize=gas.MOLAR_MASS)
m.dynamicViscosity = Param(initialize=gas.DYNAMIC_VISCOSITY)
m.gravitationalAcceleration = Param(initialize=G)
m.pipeSlope = Param(initialize=PIPE_SLOPE)
m.innerPipeRoughness = Param(initialize=PIPE_INNER_ROUGHNESS)
m.c_HT = Param(initialize=2)
m.pi = Param(initialize=pi)
m.temperatureSoil = Param(initialize=TEMPERATURE_SOIL)
m.gasConstantR = Param(initialize=GAS_CONSTANT)
m.massFlow = Param(initialize=MASS_FLOW)
m.pipeDiameter = Param(initialize=PIPE_DIAMETER)
m.crossSectionalArea = Param(initialize=m.pi * m.pipeDiameter**2 / 4)
m.alpha = Param(initialize=3.52)
m.beta = Param(initialize=-2.26)
m.gamma = Param(initialize=0.274)
m.delta = Param(initialize=-1.878)
m.e = Param(initialize=2.2)
m.d = Param(initialize=2.2)
##################################################################################
# Variables
##################################################################################
m.x = ContinuousSet(bounds=(start, end))
m.pressure = Var(m.x, bounds=pressure_bounds) #
m.dpressuredx = DerivativeVar(m.pressure, wrt=m.x, initialize=0, bounds=(-100, 100))
m.temperature = Var(m.x, bounds=temperature_bounds) #
m.dtemperaturedx = DerivativeVar(m.temperature, wrt=m.x, initialize=0, bounds=(-100, 100))
m.density = Var(m.x, bounds=density_bounds)
m.ddensitydx = DerivativeVar(m.density, wrt=m.x, initialize=0, bounds=(-100, 100))
m.z = Var(m.x, bounds=(-10, 10))
m.specificIsobaricHeatCapacity = Var(m.x)
m.idealMolarIsobaricHeatCapacity = Var(m.x, bounds=idealMolarIsobaricHeatCapacityBounds)
m.correctionIdealMolarIsobaricHeatCapacity = Var(m.x, bounds=correctionIdealMolarIsobaricHeatCapacityBounds)
m.mue_jt = Var(bounds=(-100, 100))
m.velocity = Var(m.x, bounds=velocity_bounds)
m.phiVar = Var()
##################################################################################
# Constraint rules
##################################################################################
# compressibility factor z and its derivatives; (pV/(nRT)=z
def z(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
elif formula == 'AGA':
return 1 + 0.257 * p_r - 0.533 * p_r/T_r
elif formula == 'Papay':
return 1-3.52 * p_r * exp(-2.26 * T_r) + 0.247 * p_r**2 * exp(-1.878 * T_r)
elif formula == 'ideal':
return 1
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def dzdT(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay'")
elif formula == 'AGA':
return 0.533 * p/p_c * T_c * 1/T**2
elif formula == 'Papay':
return 3.52 * p_r * (2.26/T_c) * exp(-2.26 * T_r) + 0.247 * p_r**2 * (-1.878/T_c) * exp(-1.878 * T_r)
elif formula == 'ideal':
return 0
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def dzdp(p,
T,
p_c,
T_c,
formula=None):
p_r = p/p_c
T_r = T/T_c
if formula is None:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
elif formula == 'AGA':
return 0.257 * 1/p_c - 0.533 * (1/p_c)/T_r
elif formula == 'Papay':
return -3.52 * 1/p_c * exp(-2.26 * T_r) + 0.274 * 1/(p_c**2) * 2 * p * exp(-1.878 * T_r)
elif formula == 'ideal':
return 0
else:
raise ValueError("formula must be equal to 'AGA' or 'Papay' or 'ideal'")
def make_c_compr(formula):
assert formula == 'AGA' or formula == 'Papay' or formula == 'ideal'
def _c_compr(z_var,
p,
T,
p_c,
T_c):
return z_var - z(p, T, p_c, T_c, formula=formula)
return _c_compr
_c_compr = make_c_compr(formula)
def _c_compr_rule(m, x):
return 0 == _c_compr(m.z[x],
m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature)
m.c_compr = Constraint(m.x, rule=_c_compr_rule)
# specific isobaric heat capacity: ideal + correction term
def _c_mhc_real(molarMass,
specificIsobaricHeatCapacity,
idealMolarIsobaricHeatCapacity,
correctionIdealMolarIsobaricHeatCapacity):
return molarMass * specificIsobaricHeatCapacity - (idealMolarIsobaricHeatCapacity +
correctionIdealMolarIsobaricHeatCapacity)
def _c_mhc_real_rule(m, x):
return 0 == _c_mhc_real(m.molarMass,
m.specificIsobaricHeatCapacity[x],
m.idealMolarIsobaricHeatCapacity[x],
m.correctionIdealMolarIsobaricHeatCapacity[x])
m.c_mhc_real = Constraint(m.x, rule=_c_mhc_real_rule)
# _c_mhc_ideal_Shomate
def _c_mhc_ideal_Shomate(idealMolarIsobaricHeatCapacity, A, B, C, D, E, T):
return idealMolarIsobaricHeatCapacity - (A + B * (T/1000) + C * (T/1000)**2 + D * (T/1000)**3 + E/(T/1000)**2)
def _c_mhc_ideal_Shomate_rule(m, x):
return 0 == _c_mhc_ideal_Shomate(m.idealMolarIsobaricHeatCapacity[x],
gas.SHOMATE_PARAMETERS.A,
gas.SHOMATE_PARAMETERS.B,
gas.SHOMATE_PARAMETERS.C,
gas.SHOMATE_PARAMETERS.D,
gas.SHOMATE_PARAMETERS.E,
m.temperature[x])
m.c_mhc_ideal_Shomate = Constraint(m.x, rule=_c_mhc_ideal_Shomate_rule)
# _c_mhc_corr
def make_c_mhc_corr(formula):
assert formula == 'AGA' or formula == 'Papay' or formula == 'ideal'
if formula == 'AGA':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
return correctionIdealMolarIsobaricHeatCapacity
elif formula == 'Papay':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
# m.alpha = 3.52
# m.beta = -2.26
# m.gamma = 0.274
# m.delta = -1.878
p_r = p/p_c
T_r = T/T_c
return correctionIdealMolarIsobaricHeatCapacity + R * (
(gamma * delta + 0.5 * gamma * delta**2 * T_r) * p_r**2 * T_r * exp(delta * T_r) -
(2 * alpha * beta + alpha * beta**2 * T_r) * p_r * T_r * exp(beta * T_r))
elif formula == 'ideal':
def _c_mhc_corr(correctionIdealMolarIsobaricHeatCapacity, alpha, beta, gamma, delta, p, T, p_c, T_c, R):
return correctionIdealMolarIsobaricHeatCapacity
return _c_mhc_corr
_c_mhc_corr = make_c_mhc_corr(formula)
def _c_mhc_corr_rule(m, x):
return 0 == _c_mhc_corr(m.correctionIdealMolarIsobaricHeatCapacity[x],
m.alpha,
m.beta,
m.gamma,
m.delta,
m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature,
m.gasConstantR)
m.c_mhc_corr = Constraint(m.x, rule=_c_mhc_corr_rule)
# equation of state
def _c_eos(p, T, rho, molarMass, R, z):
return rho * z * R * T - p * molarMass
def _c_eos_rule(m, x):
return 0 == _c_eos(m.pressure[x],
m.temperature[x],
m.density[x],
m.molarMass,
m.gasConstantR,
m.z[x])
m.c_eos = Constraint(m.x, rule=_c_eos_rule)
# flow velocity equation
def _c_vel_flow(q, v, rho, A):
return A * rho * v - q
def _c_vel_flow_rule(m, x):
return 0 == _c_vel_flow(m.massFlow,
m.velocity[x],
m.density[x],
m.crossSectionalArea)
m.c_vel_flow = Constraint(m.x, rule=_c_vel_flow_rule)
# a smooth reformulation of the flow term with friction: lambda(q)|q|q (=phi)
def _c_friction(phi, q, k, D, e, d, A, eta):
beta = k/(3.71 * D)
lambda_slant = 1/(2*log10(beta))**2
alpha = 2.51 * A * eta / D
delta = 2 * alpha/(beta*log(10))
b = 2 * delta
c = (log(beta) + 1) * delta**2 - (e**2 / 2)
root1 = sqrt(q**2 + e**2)
root2 = sqrt(q**2 + d**2)
return phi - lambda_slant * (root1 + b + c/root2) * q
def _c_friction_rule(m):
return 0 == _c_friction(m.phiVar,
m.massFlow,
m.innerPipeRoughness,
m.pipeDiameter,
m.e,
m.d,
m.crossSectionalArea,
m.dynamicViscosity)
m.c_friction = Constraint(rule=_c_friction_rule)
# energy balance
def _diffeq_energy(q, specificIsobaricHeatCapacity, dTdx, T, rho, z, dzdT, dpdx, g, s, pi, D, c_HT, T_soil):
return q * specificIsobaricHeatCapacity * dTdx - (q * T / (rho * z) * dzdT * dpdx) + (q * g * s) + (pi * D * c_HT * (T - T_soil))
def _diffeq_energy_rule(m, x):
# if x == start:
# return Constraint.Skip
return 0 == _diffeq_energy(m.massFlow,
m.specificIsobaricHeatCapacity[x],
m.dtemperaturedx[x],
m.temperature[x],
m.density[x],
m.z[x],
dzdT(m.pressure[x],
m.temperature[x],
m.criticalPressure,
m.criticalTemperature,
formula=formula),
m.dpressuredx[x],
m.gravitationalAcceleration,
m.pipeSlope,
m.pi,
m.pipeDiameter,
m.c_HT,
m.temperatureSoil)
m.diffeq_energy = Constraint(m.x, rule=_diffeq_energy_rule)
# momentum balance
def _diffeq_momentum(rho, dpdx, q, A, drhodx, g, s, phi, D):
return rho * dpdx - q**2 / (A**2) * drhodx / rho + g * rho**2 * s + phi / (2 * A**2 * D)
def _diffeq_momentum_rule(m, x):
# if x == start:
# return Constraint.Skip
return 0 == _diffeq_momentum(m.density[x],
m.dpressuredx[x],
m.massFlow,
m.crossSectionalArea,
m.ddensitydx[x],
m.gravitationalAcceleration,
m.pipeSlope,
m.phiVar,
m.pipeDiameter)
m.diffeq_momentum = Constraint(m.x, rule=_diffeq_momentum_rule)
##################################################################################
# Discretization
##################################################################################
discretizer = TransformationFactory('dae.finite_difference')
discretizer.apply_to(m, nfe=60, wrt=m.x, scheme='BACKWARD')
##################################################################################
# Initial conditions
##################################################################################
m.pressure[start].fix(PRESSURE)
m.temperature[start].fix(TEMPERATURE)
##################################################################################
# Objective
##################################################################################
# constant
m.obj = Objective(expr=1)
m.pprint()
##################################################################################
# Solve
##################################################################################
solver = SolverFactory('scip')
# solver = SolverFactory('scip', executable="C:/Users/t.triesch/Desktop/scipampl-7.0.0.win.x86_64.intel.opt.spx2.exe")
results = solver.solve(m, tee=True, logfile="pipe.log")
##################################################################################
# Plot
##################################################################################
distance = [i/1000 for i in list(m.x)]
p = [value(m.pressure[x])/1e6 for x in m.x]
t = [value(m.temperature[x]) for x in m.x]
rho = [value(m.density[x]) for x in m.x]
v = [value(m.velocity[x]) for x in m.x]
fig = plt.figure()
gs = fig.add_gridspec(4, hspace=0.5)
axs = gs.subplots(sharex=True)
fig.suptitle('p[start] = {0} [MPa], p[end] = {1} [MPa],\n T[start]= {2} [K],\n massFlow[:]= {3} [kg/s],\n total length: {4} m'.format(
p[0], p[-1], t[0], m.massFlow.value, PIPE_LENGTH))
axs[0].plot(distance, p, '-')
axs[0].set(ylabel='p [MPa]')
axs[0].set_ylim([0, 10])
axs[0].grid()
axs[0].set_yticks([i for i in range(0, 11)])
axs[1].plot(distance, t, '-')
axs[1].set(ylabel='T [K]')
axs[1].set_ylim([250, 350])
axs[1].grid()
axs[2].plot(distance, rho, '-')
axs[2].set(ylabel='rho [kg/m^3]')
axs[2].grid()
axs[3].plot(distance, v, '-')
axs[3].set(ylabel='v [m/s]')
axs[3].grid()
for ax in axs.flat:
ax.set(xlabel='distance [km]')
plt.show()

Adding and printing items, using lists using python

So my problem seems quite trivial, but I'm new to python and am writing a simple program that calculates the reactions of a beam. My program does that successfully, but now I want to expand the capabilities to being able to plot the shear and bending moment diagrams along each beam. My thought process is to use a list and add the shear values (for now) to that list, in increments that divides the beam into 100 segments. Afterwards I want to be able to retrieve them and use these values to plot them.
class beam:
def __init__(self, emod, i, length):
self.emod = emod
self.i = i
self.length = length
def A(self, a, p): # Calculate reaction at A
return p * (self.length - a) / self.length
def B(self, a, p): # Calculate reaction at B
return p * a / self.length
def Mc(self, a, p): # Calculate moment at C
return p * a * (self.length - a) / self.length
def delc(self, a, p):
return p * a * a * (self.length - a) ** 2 / 3 / self.emod / self.i / self.length
def delx(self, x, a, p):
beta = (self.length - a) / self.length
delta = x / self.length
return p * self.length * self.length * (self.length - a) * delta * (
1 - beta * beta - delta * delta) / 6 / self.emod / self.i
def delx1(self, x, a, p):
alpha = a / self.length
delta = x / self.length
return p * self.length * self.length * a * delta * (
1 - alpha * alpha - delta * delta) / 6 / self.emod / self.i
def maxDisplacementCoords(self, a):
return a * (1.0 / 3 + 2 * (self.length - a) / 3 / a) ** 0.5
class shearValues: # This is the class that adds the shear values to a list
def __init__(self):
self.values = []
def add_values(self, beam, a_val, p):
j = float(0)
v = beam.A(a_val, p)
while j < beam.length:
if j < a_val:
continue
elif j > a_val:
continue
elif j == a_val:
v -= p
self.values.append(v)
j += beam.length / float(100)
v += beam.B(a_val, p)
self.values.append(v)
if __name__ == '__main__':
def inertia_x(h, w, t):
iy1 = w * h * h * h / 12
iy2 = (w - t) * (h - 2 * t) ** 3 / 12
return iy1 - 2 * iy2
beam_list = []
beam1 = beam(200000000000, inertia_x(0.203, 0.133, 0.025), 5)
beam2 = beam(200000000000, inertia_x(0.254, 0.146, 0.031), 5)
beam3 = beam(200000000000, inertia_x(0.305, 0.102, 0.025), 5)
beam_list.append(beam1)
beam_list.append(beam2)
beam_list.append(beam3)
while True:
my_beam = beam_list[1]
beam_choice = input("Which beam would you like to evaluate? 1, 2 or 3 ")
if beam_choice == '1':
my_beam = beam_list[0]
elif beam_choice == '2':
my_beam = beam_list[1]
elif beam_choice == '3':
my_beam = beam_list[2]
p = float(input("Enter the required load "))
a_val = float(input("Enter displacement of point load (origin at LHS) "))
print("Ay = {}".format(my_beam.A(a_val, p)))
print("By = {}".format(my_beam.B(a_val, p)))
print("Mc = {}".format(my_beam.Mc(a_val, p)))
print("Displacement at C = {}".format(my_beam.delc(a_val, p)))
displacement = input("Do you want to calculate a specific displacement? [Y]es or [N]o ").upper()
if displacement not in 'YN' or len(displacement) != 1:
print("Not a valid option")
continue
if displacement == 'Y':
x = float(input("Enter location on beam to calculate displacement (origin on LHS) "))
if x < a_val:
print("Displacement at {} = {}".format(x, my_beam.delx(x, a_val, p)))
elif x > a_val:
print("Displacement at {} = {}".format(x, my_beam.delx1(my_beam.length - x, a_val, p)))
elif x == displacement:
print("Displacement at {} = {}".format(x, my_beam.delc(a_val, p)))
elif displacement == 'N':
continue
print("Max displacement is at {} and is = {}".format(my_beam.maxDisplacementCoords(a_val),
my_beam.delx(my_beam.maxDisplacementCoords(a_val), a_val,
p)))
# The code doesn't execute the way it is intended from here
sv = shearValues()
sv.add_values(my_beam,a_val,p)
Currently it seems as if I have created an infinite loop.
As you can see, the code is not optimized at all but any help would be appreciated. And the calculations are correct.

Python pow() function returns wrong answer

I am creating a basic RSA encryption program without using an RSA library that takes a secret message, converts each character in the string to its ASCII value, encrypts with a public key and concatenates the values, and then decrypts it using a private key and returns it to a string.
All with the principle of cipher = pow(plain,e,n) and plain = pow(cipher,d,n). My issue is that when the numbers get very large as I need d and n to be 16 digits minimum, the pow() function seems to result in an error in calculation that yields an ASCII value that is out of range to convert to a character. I've been struggling to figure out where I'm going wrong for days now. Any help is appreciated. Code below:
from random import randrange, getrandbits
def is_prime(n, k=128):
# Test if n is not even.
# But care, 2 is prime !
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
# find r and s
s = 0
r = n - 1
while r & 1 == 0:
s += 1
r //= 2
# do k tests
for q in range(k):
a = randrange(2, n - 1)
x = pow(a, r, n)
if x != 1 and x != n - 1:
j = 1
while j < s and x != n - 1:
x = pow(x, 2, n)
if x == 1:
return False
j += 1
if x != n - 1:
return False
return True
def generate_prime_candidate(length):
# generate random bits
p = getrandbits(length)
#p = randrange(10**7,9*(10**7))
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length=64):
p = 4
# keep generating while the primality test fail
while not is_prime(p, 128):
p = generate_prime_candidate(length)
return p
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def generate_keypair(p, q):
n = p * q
#Phi is the totient of n
phi = (p-1) * (q-1)
#Choose an integer e such that e and phi(n) are coprime
e = randrange(1,65537)
g = gcd(e, phi)
while g != 1:
e = randrange(1,65537)
g = gcd(e, phi)
d = multiplicative_inverse(e, phi)
return ((e, n), (d, n))
def multiplicative_inverse(e, phi):
d = 0
k = 1
while True:
d = (1+(k*phi))/e
if((round(d,5)%1) == 0):
return int(d)
else:
k+=1
def encrypt(m,public):
key, n = public
encrypted = ''
print("Your original message is: ", m)
result = [(ord(m[i])) for i in range(0,len(m))]
encryption = [pow(result[i],key,n) for i in range(0,len(result))]
for i in range(0,len(encryption)):
encrypted = encrypted + str(encryption[i])
#encrypted = pow(int(encrypted),key,n)
print("Your encrypted message is: ", encrypted)
#return result,encrypted
return encrypted, encryption
def decrypt(e,c,private):
key, n = private
print("Your encrypted message is: ", c)
print(e)
decryption = [pow(e[i],key,n) for i in range(0,len(e))]
print(decryption)
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
decrypted = ''.join(result)
print("Your decrypted message is: ",decrypted)
return result,decrypted
def fastpow(x,y,p):
res = 1
x = x%p
while(y>0):
if((y&1) == 1):
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
message = input("Enter your secret message: ")
p1 = generate_prime_number()
p2 = generate_prime_number()
public, private = generate_keypair(p1,p2)
print("Your public key is ", public)
print("Your private key is ", private)
encrypted,cipher = encrypt(message,public)
decrypt(cipher,encrypted,private)
Traceback:
File "<ipython-input-281-bce7c44b930c>", line 1, in <module>
runfile('C:/Users/Mervin/Downloads/group2.py', wdir='C:/Users/Mervin/Downloads')
File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Mervin/Downloads/group2.py", line 125, in <module>
decrypt(cipher,encrypted,private)
File "C:/Users/Mervin/Downloads/group2.py", line 100, in decrypt
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
File "C:/Users/Mervin/Downloads/group2.py", line 100, in <listcomp>
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
OverflowError: Python int too large to convert to C long
Your method multiplicative_inverse is not correct. I'm not certain what you are doing in that method with the round method and floating point division, but even if you got that part correct it would be too slow anyway, requiring O(φ) steps. The usual method for computing modular multiplicative inverses is an adaptation of the extended Euclidean algorithm, which runs in O(log(φ)2) steps. Here is a straightforward mapping from the psuedocode in the Wikipedia article to python 3 code:
def multiplicative_inverse(a, n):
t, newt = 0, 1
r, newr = n, a
while newr:
quotient = r // newr
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1:
raise ZeroDivisionError("{} is not invertible".format(a))
if t < 0:
t = t + n
return t

OverFlowError: math range error javaScript to python

I am trying to build an Action potential simulation (a graph of voltage relative to time, where the voltage values are obtained through numerically solving a couple of differential equiations). I have used the code from an online simulation of this in javaScript and am trying to translate it into python. However, due to the different ways in which python and java handle floats, I get an Overflowerror: math range error. Does anyone know how I can circumvent this in this specific situation? I am posting everything i've written and my error output:
import numpy as np
import math
import matplotlib.pyplot as plt
import random
class HH():
def __init__(self):
self.dt = 0.025
self.Capacitance = 1
self.GKMax = 36
self.GNaMax = 120
self.Gm = 0.3
self.EK = 12
self.ENa = 115
self.VRest = 10.613
self.V = 0
self.n = 0.32
self.m = 0.05
self.h = 0.60
self.INa = 0
self.IK = 0
self.Im = 0
self.Iinj = 0
self.tStop = 200
self.tInjStart = 25
self.tInjStop = 175
self.IDC = 0
self.IRand = 35
self.Itau = 1
#classmethod
def alphaN(cls,V):
if(V == 10):
return alphaN(V+0.001)
else:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
print("alphaN: ", a)
return a
#classmethod
def betaN(cls,V):
a = 0.125*math.exp(-V/80)
print("betaN: ", a)
return a
#classmethod
def alphaM(cls, V):
if (V == 25):
return alphaM(V+0.0001)
else:
a = (25 - V)/10 * (math.exp( (25-V)/10) - 1)
print("alphaM", a)
return (a)
#classmethod
def betaM(cls, V):
return 4 * math.exp(-V/18)
#classmethod
def alphaH(cls, V):
return 0.07 * math.exp(-V/20)
#classmethod
def betaH(cls, V):
return 1/(math.exp((30-V/10)+1))
def iteration(self):
aN = self.alphaN(self.V)
bN = self.betaN(self.V)
aM = self.alphaM(self.V)
bM = self.betaM(self.V)
aH = self.alphaH(self.V)
bH = self.betaH(self.V)
tauN = 1/(aN + bN)
print("tauN: ", tauN)
tauM = 1/(aM + bM)
print("tauM", tauM)
tauH = 1/(aH + bH)
print("tauH: ", tauH)
nInf = aN * tauN
print("nInf: ", nInf)
mInf = aM * tauM
print("mInf: ", mInf)
hInf = aH * tauH
print("hInf: ", hInf)
self.n += self.dt/ tauN * (nInf - self.n)
print("n: ", self.n)
self.m += self.dt/tauM * (mInf - self.m)
print("m: ", self.m)
self.h += self.dt/tauH * (hInf - self.h)
print("h: ", self.h)
self.IK = self.GKMax * self.n * self.n * self.n * self.n * (self.VRest - self.EK)
print("IK: ", self.IK)
self.INa = self.GNaMax * self.m * self.m * self.m * self.h * (self.VRest - self.ENa)
print("INa: ", self.INa)
self.Im = self.Gm * (self.VRest * self.V)
print("Im: ", self.Im)
self.V += self.dt/self.Capacitance * (self.INa + self.IK + self.Im + self.Iinj)
print("V: ", self.V)
print("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn")
return self.V
if __name__ == '__main__':
hodgkinHuxley = HH()
V_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #v_vector
Iinj_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #stim_vector
n_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
m_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
h_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
plotSampleRate = math.ceil(hodgkinHuxley.tStop/2000/hodgkinHuxley.dt) #t_vector
print("plotsamplerate: ", plotSampleRate)
i = 0
t_vector = []
for t in range(0, hodgkinHuxley.tStop+1):
t= t+hodgkinHuxley.dt
if(math.floor(t)>hodgkinHuxley.tInjStart & math.ceil(t)<hodgkinHuxley.tInjStop):
rawInj = hodgkinHuxley.IDC + hodgkinHuxley.IRand * 2 * (random.random()-0.5)
else:
rawInj = 0
hodgkinHuxley.Iinj += hodgkinHuxley.dt/hodgkinHuxley.Itau * (rawInj - hodgkinHuxley.Iinj)
hodgkinHuxley.iteration()
counter = 0
if(i == plotSampleRate):
V_vector[counter] = hodgkinHuxley.V
Iinj_vector[counter] = hodgkinHuxley.Iinj
n_vector[counter] = hodgkinHuxley.n
m_vector[counter] = hodgkinHuxley.m
h_vector[counter] = hodgkinHuxley.h
i=0;
counter+=1
i+=1
Error:
plotsamplerate: 4
alphaN: 0.05819767068693265
betaN: 0.125
alphaM 27.956234901758684
tauN: 5.458584687514421
tauM 0.03129279788667988
tauH: 14.285714285707257
nInf: 0.3176769140606974
mInf: 0.8748288084532805
hInf: 0.9999999999995081
n: 0.31998936040167786
m: 0.7089605789167688
h: 0.6006999999999995
IK: -0.5235053389507994
INa: -2681.337959108097
Im: 0.0
V: -67.0465366111762
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
alphaN: 0.00034742442109860416
betaN: 0.2889909708647963
alphaM 91515.37543280824
tauN: 3.456160731837547
tauM 1.0907358211913938e-05
tauH: 0.5000401950825147
nInf: 0.0012007546414823879
mInf: 0.9981909817434281
hInf: 1.0
n: 0.31768341581102577
m: 663.6339264765652
h: 0.6206633951393696
IK: -0.5085774931025618
INa: -2272320232559.0464
Im: -213.46946791632385
V: -56808005886.37157
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Traceback (most recent call last):
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 131, in <module>
hodgkinHuxley.iteration()
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 71, in iteration
aN = self.alphaN(self.V)
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 38, in alphaN
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
OverflowError: math range error
[Finished in 0.8s]
You can write an altered version of math.exp which will behave more like the javascript function.
def safe_exp(n):
try:
return math.exp(n)
except OverflowError:
return float('inf')
OverflowError: math range error mean that's math.exp((10-V)/10) slightly outside of the range of a double, so it causes an overflow...
You may expect that this number is infinite with:
try:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
except OverflowError:
a = (10-V)/(float('inf'))

How to solve a congruence system in python?

for the problem Ax ≡ B (MOD C) I did this, and it was okay:
def congru(a,b,c):
for i in range(0,c):
if ((a*i - b)%c)== 0 :
print(i)
Now I have to solve a system of equations, where A = ( 5x + 7y) and A= (6x + 2y),
and B= 4 and B = 12 , respectively, and C is 26.
In other words:
( 5x + 7y)≡ 4 (mod 26)
(6x + 2y)≡ 12 (mod 26)
How do I do that?
Thanks.
For the aX ≡ b (mod m) linear congruence, here is a more powerful Python solution, based on Euler's theorem, which will work well even for very large numbers:
def linear_congruence(a, b, m):
if b == 0:
return 0
if a < 0:
a = -a
b = -b
b %= m
while a > m:
a -= m
return (m * linear_congruence(m, -b, a) + b) // a
>>> linear_congruence(80484954784936, 69992716484293, 119315717514047)
>>> 45347150615590
For the X, Y system: multiply 1st equation by 2 and the 2nd one by -7, add them together and solve for X. Then substitute X and solve for Y.
This is a very fast linear congruence solver that can solve a 4096 byte number in a second. Recursion versions meet their max depth at this length:
#included if you use withstats=True, not needed otherwise
def ltrailing(N):
return len(str(bin(N))) - len(str(bin(N)).rstrip('0'))
#included if you use withstats=True, not needed otherwise
def _testx(n, b, withstats=False):
s = ltrailing(n - 1)
t = n >> s
if b == 1 or b == n - 1:
return True
else:
for j in range(0, s):
b = pow_mod(b, 2, n, withstats)
if b == n - 1:
return True
if b == 1:
return False
if withstats == True:
print(f"{n}, {b}, {s}, {t}, {j}")
if withstats == True:
print(f"{n}, {b}, {s}, {t}")
return False
def fastlinearcongruence(powx, divmodx, N, withstats=False):
x, y, z = egcditer(powx, N, withstats)
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
if x > 1:
powx//=x
divmodx//=x
N//=x
if withstats == True:
print(f"powx = {powx}, divmodx = {divmodx}, N = {N}")
x, y, z = egcditer(powx, N, withstats)
if withstats == True:
print(f"x = {x}, y = {y}, z = {z}")
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
answer = (y*divmodx)%N
if withstats == True:
print(f"answer = {answer}, mrbt = {a}, mrst = {b}, mranswer = {_testx(N, answer)}")
return answer
def egcditer(a, b, withstats=False):
s = 0
r = b
old_s = 1
old_r = a
quotient = 0
if withstats == True:
print(f"quotient = {quotient}, old_r = {old_r}, r = {r}, old_s = {old_s}, s = {s}")
while r!= 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
if withstats == True:
print(f"quotient = {quotient}, old_r = {old_r}, r = {r}, old_s = {old_s}, s = {s}")
if b != 0:
bezout_t = quotient = (old_r - old_s * a) // b
if withstats == True:
print(f"bezout_t = {bezout_t}")
else:
bezout_t = 0
if withstats == True:
print("Bézout coefficients:", (old_s, bezout_t))
print("greatest common divisor:", old_r)
return old_r, old_s, bezout_t
To use:
In [2703]: fastlinearcongruence(63,1,1009)
Out[2703]: 993
In [2705]: fastlinearcongruence(993,1,1009)
Out[2705]: 63
Also this is 100x faster than pow when performing this pow:
pow(1009, 2**bit_length()-1, 2**bit_length())
where the answer is 273.
This is equivalent to the much faster:
In [2713]: fastlinearcongruence(1009,1,1024)
Out[2713]: 273
Solved, here's the code for it:
def congru(a0,a1,a2,b0,b1,b2,c):
for i in range(0,c):
for j in range(0,c):
if ((a0*i + a1*j) - a2)%c ==0 and ((b0*i +b1*j)-b2)%c==0:
print('x: %d y: %d' %( i, j))
If you need a congruence system you can use this code.
from functools import reduce
class CI:
"""
cX=a (mod m)
"""
def __init__(self, c, a, m):
self.c = c%m
self.a = a%m
self.m = m
def solve(self, x):
return (x*self.c)%self.m == self.a
def find(cil):
espacio = reduce(lambda acc, ci: acc*ci.m, cil, 1)+1
for x in range(0, espacio):
if reduce(lambda acc, ci: acc and ci.solve(x), cil, True):
return x
print(find([CI(3, 2, 4), CI(4, 1, 5), CI(6, 3, 9)]))
this example will solve for x
3x=2 (mod 2)
4x=1 (mod 1)
6x=3 (mod 9)
To solve linear congruence system, You should use Chinese theorem of reminders.
I wrote full code using python and AppJar (AppJar is for grafics).
And You can download it from my github profile: github profile, full code there
There You can find all the functions I used.
It is very simple and I am sure You will understand the code, although it is written in serbian language.

Categories