def weibull(t1, t2, lam, k):
return 1 - exp(pow(t1 / lam,k) - pow(t2 / lam, k))
python类exp()的实例源码
def lognormvariate(self, mu, sigma):
"""Log normal distribution.
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
"""
return _exp(self.normalvariate(mu, sigma))
## -------------------- exponential distribution --------------------
def calculate_max_drawdown(self):
compounded_returns = []
cur_return = 0.0
for r in self.algorithm_returns:
try:
cur_return += math.log(1.0 + r)
# this is a guard for a single day returning -100%, if returns are
# greater than -1.0 it will throw an error because you cannot take
# the log of a negative number
except ValueError:
log.debug("{cur} return, zeroing the returns".format(
cur=cur_return))
cur_return = 0.0
compounded_returns.append(cur_return)
cur_max = None
max_drawdown = None
for cur in compounded_returns:
if cur_max is None or cur > cur_max:
cur_max = cur
drawdown = (cur - cur_max)
if max_drawdown is None or drawdown < max_drawdown:
max_drawdown = drawdown
if max_drawdown is None:
return 0.0
return 1.0 - math.exp(max_drawdown)
def lognormvariate(self, mu, sigma):
"""Log normal distribution.
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
"""
return _exp(self.normalvariate(mu, sigma))
## -------------------- exponential distribution --------------------
Gaussian_sampling.py 文件源码
项目:Lattice-Based-Signatures
作者: krishnacharya
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def Bernoulli_cosh(x):
'''
Sample according to 1/cosh(x/f)
Extends corollary 6.4 from BLISS paper
'''
powx = abs(x)
while(True):
A = Bernoulli_exp(powx) # each iteration this changes as randomness comes from Bernoulli_exp exp(-|x|/f)
if(A):
return 1
B = Bernoulli_rv(0.5) or Bernoulli_exp(powx) # has to be seperate Bernoulli_exp(powx) call as we dont want dependence on A
if not(B):
return 0
def Sign(**kwargs):
'''
Algorithm 1, Pg 12 of BLISS paper
o/p:
z,c
'''
msg, A, S, m, n, sd, q, M, kappa = kwargs['msg'], kwargs['A'], kwargs['S'], kwargs['m'], kwargs['n'], kwargs['sd'], kwargs['q'], kwargs['M'], kwargs['kappa']
m_bar = m + n
D = DiscreteGaussianDistributionLatticeSampler(ZZ**m_bar, sd)
count = 0
while(True):
y = np.array(D()) # m' x 1
reduced_Ay = util.vector_to_Zq(np.matmul(A, y), 2*q)
c = hash_iterative(np.array_str(reduced_Ay) + msg, n, kappa) # still not the hash but this is test run
b = util.crypt_secure_randint(0, 1)
Sc = np.matmul(S,c)
z = y + ((-1)**b) * Sc
try:
exp_term = exp(float(Sc.dot(Sc)) / (2*sd**2))
cosh_term = np.cosh(float(z.dot(Sc)) / (sd**2))
val = exp_term / (cosh_term * M)
except OverflowError:
print "OF"
continue
if(random.random() < min(val, 1.0)):
break
if(count > 10): # beyond 4 rejection sampling iterations are not expected in general
raise ValueError("The number of rejection sampling iterations are more than expected")
count += 1
return z, c
def Sign(**kwargs):
'''
i/p:
msg: string, which the sender wants to brodcast
A : numpy array, Verification Key dimension nxm
S : numpy array, Signing key dimension mxk
o/p:
(z,c) : signature
'''
msg, A, S, q, n, m, k, d, sd, M = kwargs['msg'],kwargs['A'],kwargs['S'],kwargs['q'],kwargs['n'],kwargs['m'],kwargs['k'],kwargs['d'],kwargs['sd'],kwargs['M']
D = DiscreteGaussianDistributionLatticeSampler(ZZ**m, sd)
count = 0
while(True):
y = np.array(D()) # discrete point in Zq^m
c = util.hash_to_baseb(util.vector_to_Zq(np.matmul(A,y), q), msg, 3, k) # 3 because we want b/w 0,1,2 small coefficients in Zq
Sc = np.matmul(S,c)
z = Sc + y #notice we didnt reduce (mod q)
try:
pxe = float(-2*z.dot(Sc) + Sc.dot(Sc))
val = exp(pxe / (2*sd**2)) / M
except OverflowError:
print "OF"
continue
if(random.random() < min(val, 1.0)):
break
if(count > 4): # beyond 4 rejection sampling iterations are not expected in general
raise ValueError("The number of rejection sampling iterations are more than expected")
count += 1
return z, c
def fit(k):
loss = 0.0
for total_n, deltas in all_deltas:
total_k = total_n
P = 1.0
for t in sorted(deltas.keys()):
delta_k, delta_n = deltas[t]
pred = total_n * math.exp(-k * t / YEAR)
loss += (total_n * P - pred)**2
P *= 1 + delta_k / total_n
total_k += delta_k
total_n += delta_n
print(k, loss)
return loss
def _rbf(x):
return math.exp(-(x)**2)
def _login(self, auth_provider, position):
self.log.info('Attempting login: {}'.format(auth_provider.username))
consecutive_fails = 0
while not auth_provider.user_login():
sleep_t = min(math.exp(consecutive_fails / 1.7), 5 * 60)
self.log.info('Login failed, retrying in {:.2f} seconds'.format(sleep_t))
consecutive_fails += 1
time.sleep(sleep_t)
if consecutive_fails == 5:
raise AuthException('Login failed five times.')
self.log.info('Login successful: {}'.format(auth_provider.username))
def score(self, ciphertext, code):
"""Score is product of word scores, unigram scores, and bigram scores.
This can get very small, so we use logs and exp."""
text = decode(ciphertext, code)
logP = (sum([log(self.Pwords[word]) for word in words(text)]) +
sum([log(self.P1[c]) for c in text]) +
sum([log(self.P2[b]) for b in bigrams(text)]))
return exp(logP)
def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)
def simulated_annealing(problem, schedule=exp_schedule()):
"[Fig. 4.5]"
current = Node(problem.initial)
for t in xrange(sys.maxint):
T = schedule(t)
if T == 0:
return current
next = random.choice(expand(node. problem))
delta_e = next.path_cost - current.path_cost
if delta_e > 0 or probability(math.exp(delta_e/T)):
current = next
def squash(self, total_net_input):
return 1 / (1 + math.exp(-total_net_input))
# Determine how much the neuron's total input has to change to move closer to the expected output
#
# Now that we have the partial derivative of the error with respect to the output (?E/?y?) and
# the derivative of the output with respect to the total net input (dy?/dz?) we can calculate
# the partial derivative of the error with respect to the total net input.
# This value is also known as the delta (?) [1]
# ? = ?E/?z? = ?E/?y? * dy?/dz?
#
def hill_climbing_first_choice_simulated_annealing(status):
'''??????????????????????????????????????
??????????
'''
global chess_status_count, temperature
pos = [(x, y) for x in range(8) for y in range(8)]
random.shuffle(pos)
for col, row in pos:
if status[col] == row:
continue
chess_status_count += 1
status_copy = list(status)
status_copy[col] = row
delta = get_num_of_conglict(status) - get_num_of_conglict(status_copy)
# ??
if temperature > 0:
temperature -= 0.0001
if delta > 0:
status[col] = row
return status
elif delta < 0 and temperature != 0:
probability = math.exp(delta / temperature)
random_num = random.random()
if random_num < probability:
status[col] = row
return status
return status
def apply_regression(self, x_reg, y_reg, width_reg, height_reg):
"""Apply offsets to bounding box."""
self.x_center += x_reg * self.width
self.y_center += y_reg * self.height
self.width *= math.exp(width_reg)
self.height *= math.exp(height_reg)
self.x_min = self.x_center - (self.width / 2.0)
self.y_min = self.y_center - (self.height / 2.0)
self.x_max = self.x_center + (self.width / 2.0)
self.y_max = self.y_center + (self.height / 2.0)
return self
def wakefield_bf(beta,se,p,w = 0.1):
# calculate Wakefield bayes factor
z = stats.norm.isf(p/2)
r = w/(se**2 + w)
bf = math.sqrt(1-r) * math.exp(z**2/2*r)
return bf
def mel_to_hertz(frequency):
return 700.0 * (math.exp(frequency / 1125.0) - 1.0)
def k1(Ti, exp=math.exp):
"""[cm^3 / s]"""
return 3.23e-12 * exp(3.72/(Ti/300) - 1.87/(Ti/300)**2)
def k2(Ti, exp=math.exp):
"""[cm^3 / s]"""
return 2.78e-13 * exp(2.07/(Ti/300) - 0.61/(Ti/300)**2)