Python math 模块,e() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.e()。
def GetFh(self,code):#??????
try:
ret = urllib.urlopen("http://money.finance.sina.com.cn/corp/go.php/vISSUE_ShareBonus/stockid/" + code + ".phtml")
soup = BeautifulSoup(Tools().smartCode(ret.read()), "html.parser")
dict = {}
for x in soup.find_all('tbody'):
for e in str(x).split('_blank'):
if "type=1" in e:
td = re.findall(r'<td>(.+?)</td>', e)
dict.update({td[0]: {u"????".encode('gbk', 'ignore').decode('gbk'): td[0],
u"??".encode('gbk', 'ignore').decode('gbk'): td[1],
u"??".encode('gbk', 'ignore').decode('gbk'): td[2],
u"??".encode('gbk', 'ignore').decode('gbk'): td[3],
u"??".encode('gbk', 'ignore').decode('gbk'): td[4],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[5],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[6],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[7]
}})
return pandas.DataFrame.from_dict(dict, orient="index")
except:
return None
def GetPg(self,code):#??????
try:
ret = urllib.urlopen("http://money.finance.sina.com.cn/corp/go.php/vISSUE_ShareBonus/stockid/" + code + ".phtml")
soup = BeautifulSoup(Tools().smartCode(ret.read()), "html.parser")
dict = {}
for x in soup.find_all('tbody'):
for e in str(x).split('_blank'):
if "type=2" in e:
td = re.findall(r'<td>(.+?)</td>', e)
dict.update({td[0]: {u"????".encode('gbk', 'ignore').decode('gbk'): td[0],
u"????".encode('gbk', 'ignore').decode('gbk'): td[1],
u"????".encode('gbk', 'ignore').decode('gbk'): td[2],
u"????".encode('gbk', 'ignore').decode('gbk'): td[3],
u"???".encode('gbk', 'ignore').decode('gbk'): td[4],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[5],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[6],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[7],
u"?????".encode('gbk', 'ignore').decode('gbk'): td[8],
}})
return pandas.DataFrame.from_dict(dict, orient="index")
except:
return None
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def evaluateStack( s ):
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
raise Exception("invalid identifier '%s'" % op)
else:
return float( op )
def evaluateStack( s ):
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
if op in variables:
return variables[op]
raise Exception("invalid identifier '%s'" % op)
else:
return float( op )
def test_Timing(self):
e = vu.ElapsedTime()
with vu.Timing(elapsed=e):
time.sleep(0.2)
self.assertAlmostEqual(e.value, 0.2, places=1)
# test some other modes of invocation
with vu.Timing() as t:
x = 1
loglvl = 10
class FakeLog:
def __init__(self, testclass):
self.tc = testclass
def log(self, lvl, msg):
self.tc.assertEqual(lvl, loglvl)
with vu.Timing(log=FakeLog(self), level=loglvl):
x = 1
def test_get_mongo(self):
"Test get_mongo() function"
import math
with self.assertRaises(ValueError):
for rec in [1, 2, 3], 'foo':
vv.mongo_get(rec, 'a')
for rec in {}, None, '':
self.assertEqual(vv.mongo_get(rec, 'a', 'dee-fault'), 'dee-fault')
rec = {'a': {
'apple': {
'red': 'delicious',
'green': 'grannysmith',
'blue': 'venutian'},
'anumber': 2, },
'e': math.e, }
default = 'mittens'
# these should be found
for key, expected in (('a.apple.green', 'grannysmith'), ('a.anumber', 2), ('e', math.e)):
self.assertEqual(vv.mongo_get(rec, key, default), expected)
# these should not
for key in 'a.apple.orange', 'x', '', 'z.zebra.', '.':
self.assertEqual(vv.mongo_get(rec, key, default), default)
def get_price_for_trade(prediction, trade):
"""Returns the price of a trade for a prediction."""
if trade.contract == 'CONTRACT_ONE':
old_quantity = prediction.contract_one
old_quantity_other = prediction.contract_two
else:
old_quantity = prediction.contract_two
old_quantity_other = prediction.contract_one
if trade.direction == 'BUY':
new_quantity = old_quantity + trade.quantity
else:
new_quantity = old_quantity - trade.quantity
price = (prediction.liquidity * math.log(
math.pow(math.e, (new_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity)))) - (
prediction.liquidity * math.log(
math.pow(math.e, (old_quantity / prediction.liquidity)) +
math.pow(math.e, (old_quantity_other / prediction.liquidity))))
return price
def getForegroundMask(self):
'''
@return: A mask image indicating which pixels are considered foreground.
Depending on whether soft-thresholding is used, this may be a binary image
with values of [0 or 255], or image of weights [0.0-255.0], which will
have to be divided by 255 to get weights [0.0-1.0].
@note: One may wish to perform additional morphological operations
on the foreground mask prior to use.
'''
diff = self._computeBGDiff()
if self._softThreshold:
mask = 1 - (math.e)**(-(1.0*diff)/self._threshold) #element-wise exp weighting
#mask = (diff > self._threshold)
else:
mask = (sp.absolute(diff) > self._threshold)
#mu = sp.mean(diff)
#sigma = sp.std(diff)
#mask = sp.absolute((diff-mu)/sigma) > self._threshold
return pv.Image(mask*255.0)
def _PrintResiduals(self, slope, intercept):
independent_dict = None
dependent_dict = None
if len(self._county_idata) > 0 and len(self._county_ddata) > 0:
independent_dict = self._county_idata
dependent_dict = self._county_ddata
else:
independent_dict = self._independent_data
dependent_dict = self._dependent_data
for precinct,logvotes in sorted(independent_dict.iteritems()):
if precinct not in dependent_dict:
continue
actual = int(math.e**dependent_dict[precinct])
predict_exponent = intercept + slope*logvotes
predict = int(math.e**predict_exponent)
diff = actual - predict
pct_error = (1.0 * diff) / predict
print('%-38s\t%7d\t%7d\t%7d\t%7.4f' % (precinct, actual, predict, diff, pct_error))
def get_theta():
import math
theta = [0.0, 0.0, 0.0]
step = 0.01
comments = Comment.query.all()[:100]
print "Comments gotten! Training..."
for m in range(1000):
for comment in comments:
if comment.emotion != -1:
x = [1, float(comment.pos_count), float(comment.neg_count)]
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
h = 1 / (1+math.e**-(feature_sum))
for i in range(3):
theta[i] = theta[i] + step*(comment.emotion-h)*x[i]
print "Theta Gotten: ", theta
def get_emotion():
print "Calculating thetas..."
get_theta()
print "Done!"
comments = Comment.query.filter_by(emotion=-1).all()
for comment in comments:
x = [1, float(comment.pos_count), float(comment.neg_count)]
hypothesis = 0
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
hypothesis = 1 / (1+math.e**-(feature_sum))
if 0 < hypothesis < 0.4:
comment.analysis_score = 0
elif 0.4 <= hypothesis < 0.6:
comment.analysis_score = 0.5
elif 0.6 <= hypothesis < 1:
comment.analysis_score = 1
def get_stats_and_update_occupancy(CG, sorted_nodes, tfile) :
"""
Update the occupancy in the Graph and the total simulation time
"""
# http://www.regular-expressions.info/floatingpoint.html
reg_flt = re.compile('[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?.')
lastlines = s.check_output(['tail', '-2', tfile]).strip().split("\n")
if not reg_flt.match(lastlines[0]):
raise ValueError('Cannot parse simulation output', tfile)
else :
time = float(lastlines[0].split()[0])
iterations = int(lastlines[-1].split()[-1])
tot_occ =sum(map(float, lastlines[0].split()[1:]))
for e, occu in enumerate(lastlines[0].split()[1:]) :
ss = sorted_nodes[e][0]
CG.node[ss]['occupancy'] = float(occu)/tot_occ
return time, iterations
def evaluateStack( s ):
try:
op = s.pop()
if op == 'unary -':
return -evaluateStack( s )
if op in "+-*/^":
op2 = evaluateStack( s )
op1 = evaluateStack( s )
return opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in fn:
return fn[op]( evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
except:
return None
def test_use_decimal():
import math
from decimal import Decimal
dstr = "2.7182818284590452353602874713527"
d = Decimal(dstr)
with pytest.raises(TypeError):
rapidjson.dumps(d)
assert rapidjson.dumps(float(dstr)) == str(math.e)
assert rapidjson.dumps(d, use_decimal=True) == dstr
assert rapidjson.dumps({"foo": d}, use_decimal=True) == '{"foo":%s}' % dstr
assert rapidjson.loads(
rapidjson.dumps(d, use_decimal=True),
use_decimal=True) == d
assert rapidjson.loads(rapidjson.dumps(d, use_decimal=True)) == float(dstr)
def poisson_distribution(gamma):
"""Computes the probability of events for a Poisson distribution.
Args:
gamma: The average number of events to occur in an interval.
Returns:
The probability distribution of k events occuring.
This is a function taking one parameter (k) and returning the
probability of k events occuring.
"""
constant_factor = math.e ** (-gamma)
def probability(k):
"""The probability of k events occuring for a Poisson distribution.
Args:
k: The number of the events occuring in an interval.
Returns:
The probability of k events occuring in the given distribution.
"""
return (constant_factor * gamma ** k) / (math.factorial(k))
return probability
def _createGameFromData(self, gameData):
temp = int(gameData['Template'])
tempID, tempSettings, overrides = self._getTempSettings(temp)
teams = self._assembleTeams(gameData)
try:
wlID = self.handler.createGame(tempID, self._getGameName(gameData),
teams, settingsDict=tempSettings,
overridenBonuses=overrides,
teamless=self.teamless,
message=self._getGameMessage(gameData))
self._adjustTemplateGameCount(temp, 1)
createdStr = datetime.strftime(datetime.now(), self.TIMEFORMAT)
self._updateEntityValue(self.games, gameData['ID'],
WarlightID=wlID, Created=createdStr)
return gameData
except Exception as e:
sides = gameData['Sides']
self.parent.log("Failed to make game with %s on %d because of %s" %
(sides, temp, repr(e)), self.name, error=True)
self._deleteGame(gameData, False, False)
def _createBatch(self, batch):
currentID = self._getBatchStartingID()
for game in batch:
try:
self._addEntity(self.games,
{'ID': currentID, 'WarlightID': '', 'Created': '',
'Winners': '', 'Sides': game['Sides'], 'Vetos': 0,
'Vetoed': '', 'Finished': '',
'Template': game['Template']})
self._makeGame(currentID)
currentID += 1
except (SheetErrors.DataError, SheetErrors.SheetError) as e:
self.parent.log(("Failed to add game to sheet due to %s" %
str(e)), self.name, error=True)
except APIError as e:
self.parent.log(("Failed to create game with ID %d" %
(currentID)), self.name, error=True)
def test_nfloat_ops_binary():
# Signedness (nfloat + nfloat)
assert (nfloat( exponent=4 ) + nfloat( exponent=4 )).e == 4
assert (nfloat( exponent=4 ) + nfloat( exponent=8 )).e == 8
assert (nfloat( exponent=8 ) + nfloat( exponent=4 )).e == 8
assert (nfloat( exponent=8 ) + nfloat( exponent=8 )).e == 8
# Size (nfloat + nfloat)
assert (nfloat( mantissa=4 ) + nfloat( mantissa=4 )).m == 4
assert (nfloat( mantissa=4 ) + nfloat( mantissa=8 )).m == 8
assert (nfloat( mantissa=8 ) + nfloat( mantissa=4 )).m == 8
assert (nfloat( mantissa=8 ) + nfloat( mantissa=8 )).m == 8
# Signedness (nfloat + float)
assert (nfloat( exponent=4 ) + 0.0).e == 4
assert (nfloat( exponent=8 ) + 0.0).e == 8
# Size (nfloat + float)
assert (nfloat( mantissa=4 ) + 0.0).m == 4
assert (nfloat( mantissa=8 ) + 0.0).m == 8
# Arithmetic
assert float32(3.0) + float32(2.0) == float32(5.0)
assert float32(3.0) - float32(2.0) == float32(1.0)
assert float32(3.0) * float32(2.0) == float32(6.0)
assert float32(3.0) / float32(2.0) == float32(1.5)
assert float32(3.0) // float32(2.0) == float32(1.0)
assert float32(7.0) % float32(5.0) == float32(2.0)
assert float32(3.0) ** float32(4.0) == float32(81.0)
def test_nfloat_ops_reflected():
# Exponent size (float <op> nfloat)
assert (0.0 + nfloat( exponent=4 )).e == 4
assert (0.0 + nfloat( exponent=8 )).e == 8
assert (0.0 + nfloat( exponent=4 )).e == 4
assert (0.0 + nfloat( exponent=8 )).e == 8
# Mantissa size (float <op> nfloat)
assert (0.0 + nfloat( mantissa=4 )).m == 4
assert (0.0 + nfloat( mantissa=8 )).m == 8
assert (0.0 + nfloat( mantissa=4 )).m == 4
assert (0.0 + nfloat( mantissa=8 )).m == 8
# Arithmetic
assert 3.0 + float32(2.0) == float32(5.0)
assert 3.0 - float32(2.0) == float32(1.0)
assert 3.0 * float32(2.0) == float32(6.0)
assert 3.0 / float32(2.0) == float32(1.5)
assert 3.0 // float32(2.0) == float32(1.0)
assert 7.0 % float32(5.0) == float32(2.0)
assert 3.0 ** float32(4.0) == float32(81.0)
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def kullback_leibler_divergence(prob_dist1, prob_dist2, base=math.e):
# Calculate the Kullback-Leibler divergence
kl_divergence = 0
# To avoid zero in the numerator or denominator
pseudo_count = 0.000001
for index in range(len(prob_dist1)):
#print 'KL Divergence PD1[{0}]: {1} PD2[{0}]: {2}'.format(index, prob_dist1[index], prob_dist2[index])
#print "newdiv == {0}".format(newdiv(float(prob_dist1[index]) + pseudo_count, float(prob_dist2[index]) + pseudo_count))
#kl_divergence += prob_dist1[index] * math.log(newdiv(float(prob_dist1[index]) + pseudo_count, float(prob_dist2[index]) + pseudo_count), base)
kl_divergence += prob_dist1[index] * math.log((float(prob_dist1[index]) + pseudo_count) / (float(prob_dist2[index]) + pseudo_count), base)
return kl_divergence
def jensen_shannon_divergence(prob_dist1, prob_dist2, base=math.e):
# Calculate "M" == (prob_dist1 + prob_dist2) / 2
# m = []
len_pd1 = len(prob_dist1)
m = [0.5 * (prob_dist1[index] + prob_dist2[index]) for index in range(len_pd1)]
# for index in range(0, len(prob_dist1)):
# m.append(0.5 * (prob_dist1[index] + prob_dist2[index]))
#print 'M: {0}'.format(m)
# Return Jensen-Shannon Divergence
jsd = 0.5 * (kullback_leibler_divergence(prob_dist1, m, base) + kullback_leibler_divergence(prob_dist2, m, base))
#print 'Jensen-Shannon Divergence: {0}'.format(jsd)
return jsd
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4
def annealing_optimize(domain, cost_fuc, t=10000.0, cool=0.95, step=1):
vec = [float(random.randint(domain[i][0], domain[i][1])) for i in range(len(domain))]
while t > 0.1:
i = random.randint(0, len(domain)-1)
direction = random.randint(-step, step)
new_vec = vec[:]
new_vec[i] += direction
if new_vec[i] < domain[i][0]:
new_vec[i] = domain[i][0]
elif new_vec[i] > domain[i][1]:
new_vec[i] = domain[i][1]
cost = cost_fuc(vec)
new_cost = cost_fuc(new_vec)
# ?? pow(math.e, -(new_cost-cost)/t) ???????
# ?new_cost > cost ?????t????????new_cost
# ??t????????????new_cost
# ??t???????????new_cost
if new_cost < cost or random.random() < pow(math.e, -(new_cost+cost)/t):
vec = new_vec
t *= cool
return vec, cost_fuc(vec)
def run_cc(self, cmd, msg):
gid = str(msg.guild.id)
if self.ccs[gid][cmd]["locked"] and not msg.author.guild_permissions.manage_messages:
await respond(msg, f"**WARNING: Custom command {cmd} is locked.**")
else:
ccdat = self.ccs[gid][cmd]["content"]
try:
res = self._find_tags(ccdat, msg)
except CustomCommandSyntaxError as e:
err = e if e else "Syntax error."
await respond(msg, f"**WARNING: Author made syntax error: {err}**")
except CommandSyntaxError as e:
err = e if e else "Syntax error."
await respond(msg, f"**WARNING: {err}**")
except Exception:
self.logger.exception("Exception occurred in custom command: ", exc_info=True)
await respond(msg, "**WARNING: An error occurred while running the custom command.**")
else:
if res:
await respond(msg, res)
else:
self.logger.warning(f"CC {cmd} of {str(msg.guild)} returns nothing!")
self.ccvars = {}
self.ccs[gid][cmd]["times_run"] += 1
self._save_ccs()
def upper_incomplete_gamma(a,x,d=0,iterations=100):
if d == iterations:
if ((d % 2) == 1):
return 1.0 # end iterations
else:
m = d/2
return x + (m-a)
if d == 0:
result = ((x**a) * (e**(-x)))/upper_incomplete_gamma(a,x,d=d+1)
return result
elif ((d % 2) == 1):
m = 1.0+((d-1.0)/2.0)
return x+ ((m-a)/(upper_incomplete_gamma(a,x,d=d+1)))
else:
m = d/2
return 1+(m/(upper_incomplete_gamma(a,x,d=d+1)))
# 6.5.31 Handbook of Mathematical Functions, page 263
# Recursive implementation
def lower_incomplete_gamma(a,x,d=0,iterations=100):
if d == iterations:
if ((d % 2) == 1):
return 1.0 # end iterations
else:
m = d/2
return x + (m-a)
if d == 0:
result = ((x**a) * (e**(-x)))/lower_incomplete_gamma(a,x,d=d+1)
return result
elif ((d % 2) == 1):
m = d - 1
n = (d-1.0)/2.0
return a + m - (((a+n)*x)/lower_incomplete_gamma(a,x,d=d+1))
else:
m = d-1
n = d/2.0
return a+m+((n*x)/(lower_incomplete_gamma(a,x,d=d+1)))
def test_constants():
for prec in [3, 7, 10, 15, 20, 37, 80, 100, 29]:
mp.dps = prec
assert pi == mpf(tpi)
assert e == mpf(te)
assert degree == mpf(tdegree)
assert euler == mpf(teuler)
assert ln2 == mpf(tln2)
assert ln10 == mpf(tln10)
assert catalan == mpf(tcatalan)
assert khinchin == mpf(tkhinchin)
assert glaisher == mpf(tglaisher)
assert phi == mpf(tphi)
if prec < 50:
assert mertens == mpf(tmertens)
assert twinprime == mpf(ttwinprime)
mp.dps = 15
assert pi >= -1
assert pi > 2
assert pi > 3
assert pi < 4
def _normal_function(x, mean, variance):
"""
Find a value in the cumulative distribution function of a normal curve.
See https://en.wikipedia.org/wiki/Normal_distribution
Args:
x (float): Value to feed into the normal function
mean (float): Mean of the normal function
variance (float): Variance of the normal function
Returns: float
Example:
>>> round(_normal_function(0, 0, 5), 4)
0.1784
"""
e_power = -1 * (((x - mean) ** 2) / (2 * variance))
return (1 / math.sqrt(2 * variance * math.pi)) * (math.e ** e_power)
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
def evaluate(self):
self._set_ready()
condition = self.get_parameter_value(self.condition)
if not condition: return
input_value = self.get_parameter_value(self.input_value)
if isinstance(input_value, numbers.Number):
for e in range(0, input_value):
self._set_value(e)
for cell in self.output_cells: cell.evaluate()
else:
for e in input_value:
self._set_value(e)
for cell in self.output_cells: cell.evaluate()
pass
pass
for cell in self.output_cells:
cell.reset()
pass
pass
def train(self):
m = self.m
for k in range(self.itern):
cls = self.estimator(max_depth = 3, presort = True)
cls.fit(self.X, self.y, sample_weight = self.w)
self.estimators.append(cls)
y_predict = cls.predict(self.X)
error = 0 # number of wrong prediction
for i in range(m):
if y_predict[i] != self.y[i]:
error += self.w[i]
if error == 0:
error += 0.01 # smoothness
alpha = 0.5*log((1-error)/error) # estimator weight
self.alphas = np.append(self.alphas, alpha)
for i in range(m): # update sample weights
if y_predict[i] != self.y[i]:
self.w[i] *= e**alpha
else:
self.w[i] /= e**alpha
self.w /= sum(self.w)
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def ok(f):
global PASS, FAIL
if THE.tests:
try:
print("\n-----| %s |-----------------------" % f.__name__)
if f.__doc__:
print("# "+ re.sub(r'\n[ \t]*',"\n# ",f.__doc__))
f()
print("# pass")
PASS += 1
except Exception,e:
FAIL += 1
print(traceback.format_exc())
return f
### LIB.tiles ##################################################
def mutate(old, abouts, pop=[], better= lambda x,y,z: cdom(x,y,z),
fiddles= None, # e.g. de. maxWalkSat
fiddle = any1thing, # e.g. around1 or any1thing
after = wrap, # e.g. wrap or cap
retries= THE.retries):
assert retries > 0, 'too hard to satisfy model'
new = abouts.copyDecs(old)
if fiddle:
for col in abouts._decs:
if r() < THE.cf:
new[col.pos] = fiddle(old[col.pos], col) # eg around1, any1thing
if fiddles:
new = fiddles(old,new,abouts,pop, better) # eg deFiddles maxWalkSatFiddles
if after: # e.g. wrap cap
for col in abouts._decs:
new[col.pos] = after(new[col.pos], col)
return new if abouts.ok(new) else mutate(old, abouts, pop,better,
fiddles,fiddle, after,
retries=retries-1)
### Tables #####################################################################
def cdom(x, y, abouts):
"many objective"
x= abouts.objs(x)
y= abouts.objs(y)
def w(better):
return -1 if better == less else 1
def expLoss(w,x1,y1,n):
return -1*math.e**( w*(x1 - y1) / n )
def loss(x, y):
losses= []
n = min(len(x),len(y))
for obj in abouts._objs:
x1, y1 = x[obj.pos] , y[obj.pos]
x1, y1 = obj.norm(x1), obj.norm(y1)
losses += [expLoss( w(obj.want),x1,y1,n)]
return sum(losses) / n
l1= loss(x,y)
l2= loss(y,x)
return l1 < l2
def gaussian_blur(cls, self, radius, n=3):
if self.mode == 'RGBA':
return cls.gaussian_blur(self.convert('RGBa'),
radius, n).convert('RGBA')
if self.mode == 'LA':
return cls.gaussian_blur(self.convert('La'),
radius, n).convert('LA')
# http://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf
# [7] Box length.
L = math.sqrt(12.0 * float(radius) * radius / n + 1.0)
# [11] Box radius.
l = (L - 1.0) / 2.0
# Integer part.
li = math.floor(l)
# Reduce the fractional part in accordance with tests.
a = math.e ** (2.5 * (l - li) / (li + 1)) - 1
a /= math.e ** (2.5 / (li + 1)) - 1
box_radius = li + a
self.load()
return self._new(self.im.box_blur(box_radius, n))
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def emp_cdf(samples,x):
''' Indicator Function for Empirical Distribution:
1: if X_i <= x
0: otherwise
sample = X_i
'''
def indicator(sample):
# Note: This function will grab the value of "x" from the scope of the parent function.
if sample <= x: return 1
else: return 0
sigma = 0
n = len(samples)
for X_i in samples:
sigma += indicator(X_i)
return (1/n) * sigma
# Function is a string with a matematical expression, e.g. function='x+5'
# Input: function is a f: R --> R
def __init__(self):
"""
'code_word' ????key???list?value?dict??????????
'word_code' ????key????value?dict????????????
'vocab' ?????
'N' N????????????
"""
self.a = 0.65
self.b = 0.8
self.c = 0.9
self.d = 0.96
self.e = 0.5
self.f = 0.1
self.degree = 180
self.PI = math.pi
self.code_word = {}
self.word_code = {}
self.vocab = set()
self.N = 0
self.read_cilin()
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def ntk(self, ra, da, rb, db, hra, hrb):
if hra < hrb:
tmpkey = str(hra) + "#" + str(hrb)
else:
tmpkey = str(hrb) + "#" + str(hra)
if self.cache.exists(tmpkey):
return float(self.cache.read(tmpkey))
lena,lenb = len(ra), len(rb)
c, p, minlen = 0, 0, min(lena,lenb)
while c < minlen and ra[c] == rb[c]:
if ra[c] == "#": p += 1
c += 1
#print "p = ", p, "da, db", da, db, ra, rb
if self.gamma == 1:
r = (p+1)*(math.e**(-self.beta*(da + db - 2*p)))
else:
r = (1-self.gamma**(p+1))/(1-self.gamma)*(math.e**(-self.beta*(da + db - 2*p)))
if len(self.cache) > self.cachesize:
self.cache.removeAll()
self.cache.insert(tmpkey,r)
return r
# if self.gamma == 1:
# return (p+1)*(math.e**(-self.beta*(da + db - 2*p)))
# else:
# return (1-self.gamma**(p+1))/(1-self.gamma)*(math.e**(-self.beta*(da + db - 2*p)))
def test_import(self):
self.assert_ok("""\
import math
print(math.pi, math.e)
from math import sqrt
print(sqrt(2))
""")
def evaluateStack(self, s ):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack( s )
if op in "+-x/^":
op2 = self.evaluateStack( s )
op1 = self.evaluateStack( s )
return self.opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op]( self.evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
def Incap(self):
df1 = self.sharedf
incap=[]
for x in df1['market_value']:
incap.append(math.log(x,math.e))
df1['incap'] = incap
return df1[['date','incap']]
def expmin(values, num):
"""
Return a list of `num` exponentially distributed numbers from the
list `values`, starting at the lowest one. The base is the constant `e`.
"""
l = len(values)
v = []
for i in range(num):
index = int((exp(i / num) - 1.0) / (e - 1.0) * l)
index = clipint(index, l)
v.append(values[index])
return v
def expmax(values, num):
"""
Return a list of `num` exponentially distributed numbers from the
list `values`, starting at the highest one. The base is the constant `e`.
"""
l = len(values)
last = l - 1
v = []
for i in range(num):
index = last - int((exp(i / num) - 1.0) / (e - 1.0) * l)
index = clipint(index, l)
v.append(values[index])
return v