def get_ellipse_table(y_radius): global ellipses_table if ellipses_table.has_key(y_radius): return ellipses_table[y_radius] x_radius = y_radius / 2 ellipse_table = {} split_point = y_radius - 0.5 for y in range(y_radius, 0, -1): yy = y * y val1 = operator.div(yy, float(y_radius * y_radius)) val2 = operator.sub(1.0, val1) x_squared = (float(x_radius * x_radius)) * val2 x_offset_float = math.sqrt(operator.abs(x_squared)) x_offset = int(math.ceil(x_offset_float)) y_offset = operator.abs(y - y_radius) ellipse_table[y_offset] = x_offset ellipse_table[int(2*split_point) - y_offset] = x_offset pair = (ellipse_table, x_radius) ellipses_table[y_radius] = pair return pair
def testPython(self): def F(u): return div(grad(u)) famms = Famms(2, simtype="Python") (x, y) = famms.x v = sin(x)*cos(y) famms.assign(equation=F, solution=v) (solution, source) = famms.getCallbacks() pt = (1.0, 1.0) print "\nThe callbacks return the folloging values at the points (%f, %f)" % (pt[0], pt[1]) print "Analytical solution:\t%10f" % solution.evalPt(pt) print "Source term:\t\t%10f" % source.evalPt(pt) import math import operator epsilon = 1e-15 # Allow slightly different answers due to different number handling print "\nThe precomputed solution at this point is:" print "Analytical solution:\t%10f" % (math.sin(pt[0]) * math.cos(pt[1])) print "Source term:\t\t%10f" % (-2*math.sin(pt[0])*math.cos(pt[1])) assert operator.abs(solution.evalPt(pt) - math.sin(pt[0]) * math.cos(pt[1])) < epsilon assert operator.abs(source.evalPt(pt) - -2*math.sin(pt[0])*math.cos(pt[1])) < epsilon
def testAverageNormals(poly): # These logs are commented out because they slow down the script considerably. They are for debugging purposes. # Application.LogMessage("Working from polygon index %s" % poly.index) oAdjacentPolys = poly.GrowNeighborPolygons(oTargetGrowAmount) XYZListCount = 0 oNormalXList = 0 oNormalYList = 0 oNormalZList = 0 for polys in oAdjacentPolys: oPolysNode = polys.Nodes(0) oPolysNormal = oPolysNode.Normal oNormalXList+=(oPolysNode.Normal.X) oNormalYList+=(oPolysNode.Normal.Y) oNormalZList+=(oPolysNode.Normal.Z) XYZListCount+=1 # Application.LogMessage("%(what)s %(numb)s is a polygon adjacent to the current one with normal %(nx)s, %(ny)s, %(nz)s" % {"numb":polys.index,"what":polys.Type,"nx":oPolysNormal.X,"ny":oPolysNormal.Y,"nz":oPolysNormal.Z}) oAverageNormalX = div(oNormalXList,XYZListCount) oAverageNormalY = div(oNormalYList,XYZListCount) oAverageNormalZ = div(oNormalZList,XYZListCount) NormalXRef = poly.Nodes(0).Normal.X NormalYRef = poly.Nodes(0).Normal.Y NormalZRef = poly.Nodes(0).Normal.Z deltax = abs(oAverageNormalX-NormalXRef) deltay = abs(oAverageNormalY-NormalYRef) deltaz = abs(oAverageNormalZ-NormalZRef) # Application.LogMessage("Total Normal delta for poly index %(polyindex)s is %(deltasum)s" % {"polyindex":poly.index,"deltasum":(deltax+deltay+deltaz)}) if ((deltax+deltay+deltaz)>oNormalReverseThreshold): return 1 else: return 0
def test_fit(): import random random.seed(1234) n = Normal.fit(Uniform.fit(Normal(2, 1.5).random(1000))) # print n.mean # print n.stddev assert abs(n.mean - 2) < 0.3 assert abs(n.stddev - 1.5) < 0.3
def slopeCalculation(pt1,pt2): dx2=operator.pow(operator.abs(operator.sub(pt1.X,pt2.X)),2) dy2=operator.pow(operator.abs(operator.sub(pt1.Y,pt2.Y)),2) dz2=operator.pow(operator.abs(operator.sub(pt1.Z,pt2.Z)),2) if dz2>0: vertical=operator.pow(dz2,0.5) horiz=operator.pow(dx2+dy2,0.5) slope=(vertical/horiz)*100 else: slope=999 return slope
def test_fit(): import random random.seed(1234) n = Normal.fit(Uniform.fit(Normal(2, 1.5).random(1000))) #print n.mean #print n.stddev assert abs(n.mean - 2) < 0.3 assert abs(n.stddev - 1.5) < 0.3 n = Normal.fit([1,2,3,4,5]) assert n.mean == 3 assert n.stddev == sqrt(2) n = Uniform.fit([1,2,3,4,5]) assert n.mean == 3 assert n.stddev == sqrt(2)
def test_fit(): import random random.seed(1234) n = Normal.fit(Uniform.fit(Normal(2, 1.5).random(1000))) #print n.mean #print n.stddev assert abs(n.mean - 2) < 0.3 assert abs(n.stddev - 1.5) < 0.3 n = Normal.fit([1, 2, 3, 4, 5]) assert n.mean == 3 assert n.stddev == sqrt(2) n = Uniform.fit([1, 2, 3, 4, 5]) assert n.mean == 3 assert n.stddev == sqrt(2)
def do_move(particles): min_distance = 999999 min_particle = -1 for p in particles: pos = p["pos"] vel = p["vel"] acc = p["acc"] vel = tuple(map(add, vel, acc)) pos = tuple(map(add, pos, vel)) p["pos"] = pos p["vel"] = vel # Calculate the haversine distance. new_dist = sum(abs(x) for x in pos) if new_dist < min_distance: min_distance = new_dist min_particle = p p["dist"] = new_dist return min_distance, min_particle["id"]
def implied_volatility(s, x, r, tau, mp, option_type="call", precision=1e-4, iterations=100): """ Newton-Raphson method of successive approximations to find implied volatility Args: s (float): stock price x (float): strike price r (float): risk-free interest rate tau (float): time to option expiration expressed in years mp (float): market price of an option option_type (str): specify option type: "call" or "put" precision (float): threshold below which to accept volatility estimate iterations (int): number of rounds of estimations to conduct Returns: float: closest estimation for implied volatility """ # initial estimation sigma = 0.5 for i in range(0, iterations): # price of an option as per Black Scholes bs_p = option_price(s, x, r, sigma, tau, option_type) diff = mp - bs_p # check if difference is acceptable if (operator.abs(diff) < precision): return sigma vega = _vega(s, x, r, sigma, tau) # update sigma with addition of difference divided by derivative sigma = sigma + (diff / vega) print(sigma) # closest estimation return sigma
def ConvertToThreeCoulmnsInput(inputfilename, outputfilename='', outputfilepath=''): if (outputfilename == ''): outputfilename, ex = os.path.splitext(inputfilename) outputfilename = outputfilename + "_converted.csv" outputfilename = outputfilepath + outputfilename print(("Converting input file " + inputfilename + " to intermediate three columns input file " + outputfilename + " in path " + outputfilepath + " ...")) #read file into pandas dataframe table = pd.read_csv(inputfilename) #create column that is term_ID but without GO: and leading zeroes table['term_ID_int'] = [int(item.split(':')[1]) for item in table.term_ID] # replace numeric reference to GO id with corresponding textual description table['representative'] = \ [table[table['term_ID_int']==representative].description.values[0] for representative in table.representative] # rename column table.rename(columns={'log10 p-value': 'log10pvalue'}, inplace=True) # convert log10pvalue values to their absoulute values table['log10pvalue'] = abs(table['log10pvalue']) # save only three columns to _converted.csv for further preprocessing table[['description', 'log10pvalue', 'representative']].to_csv(outputfilename, index=False, sep='\t')
def main(): a = -1 b = 5.0 c = 2 d = 6 for k, v in {"a": a, "b": b, "c": c, "d": d}.items(): print(k + " =", v) print("\nPositive/Negative:") print("abs(a);", operator.abs(a)) print("neg(a);", operator.neg(a)) print("neg(b);", operator.neg(b)) print("pos(a);", operator.pos(a)) print("pos(b);", operator.pos(b)) print("\nArithmetic:") print("add(a, b) :", operator.add(a, b)) print("floordiv(a, b):", operator.floordiv(a, b)) print("floordiv(d, c):", operator.floordiv(d, c)) print("mod(a, b) :", operator.mod(a, b)) print("mul(a, b) :", operator.mul(a, b)) print("pow(c, d) :", operator.pow(c, d)) print("sub(b, a) :", operator.sub(b, a)) print("truediv(a, b) :", operator.truediv(a, b)) print("truediv(d, c) :", operator.truediv(d, c)) print("\nBitwise:") print("and_(c, d) :", operator.and_(c, d)) print("invert(c) :", operator.invert(c)) print("lshift(c, d):", operator.lshift(c, d)) print("or_(c, d) :", operator.or_(c, d)) print("rshift(d, c):", operator.rshift(d, c)) print("xor(c, d) :", operator.xor(c, d))
def planeln (plane, ptA1, ptA2): #determines the intersection point, or identify its parallelism ptA1 = ptCheck(ptA1) ptA2 = ptCheck(ptA2) plane = planeCheck(plane) #vector geometry calculation if dist(ptA1,ptA2) < 0.001: print ("Line distance too short") exit() vecA = vecSub(ptA2,ptA1) #vectorA pDist = vecSub(ptA1,plane[0]) #distance between static point of plane and line den = vecDot(vecMult(vecA,-1), plane[3]) if op.abs(den) < 0.001: print "No unique solution" return (1, "No Unique Solution") crossU = vecCross(plane[2],vecMult(vecA,-1)) crossV = vecCross(vecMult(vecA,-1),plane[1]) t = vecDot(plane[3],pDist) / den u = vecDot(crossU,pDist) / den v = vecDot(crossV,pDist) / den pointF = vecAdd(ptA1,vecMult(vecA,-t)) return (0,t,pointF)
def func(kg, m): # return protectedDiv(kg, mul(m, m)) #return abs(protectedDiv(mul(protectedDiv(kg, m), add(m, kg)), neg(neg(mul(add(m, kg), m))))) # Scores: (2.429324850286968, 1000.0) #return protectedDiv(abs(kg), mul(m, m)) # Scores: (2.429324850287263, 1000.0) return abs(protectedDiv(kg, mul(m, m))) # Scores: (2.429324850287263, 1000.0)
def _eval_apply_evalf(cls, arg): # XXX this is weird!!! # XXX remove me when 'abs -> abs_' is done arg = arg.evalf() if arg.is_Number: import operator return operator.abs(float(arg))
def _eval_apply_evalf(cls, arg): # XXX this is weird!!! # XXX remove me when 'abs -> abs_' is done arg = arg.evalf() if isinstance(arg, Basic.Number): import operator return operator.abs(float(arg))
def abs(self, *args): if not len(args) is 1: raise EvaluateException('Abs requires 1 parameter!') elif not isinstance(args[0], NumberType): raise EvaluateException('Abs requires all parameters to be numbers!') return op.abs(args[0])
def abs(self, *args): if not len(args) is 1: raise EvaluateException('Abs requires 1 parameter!') elif not isinstance(args[0], NumberType): raise EvaluateException( 'Abs requires all parameters to be numbers!') return op.abs(args[0])
def say(score0, score1): if score0 > score1: leader = 0 elif score1 > score0: leader = 1 else: leader = None if leader != None and leader != previous_leader: print('Player', leader, 'takes the lead by', abs(score0 - score1)) return announce_lead_changes(leader)
def comeback_strategy(score,opponent_score,num_rolls=num_rolls): rolls=num_rolls from operator import abs if abs(score-opponent_score)>=margin: rolls+=1 else: rolls print('num_rolls from make_comeback_strategy',num_rolls) num_rolls=rolls return always_roll(num_rolls)
def test_unit(scalar): """ Test that the unit property returns the expected unit vector. """ # Arrange expected_vector = Vector2D.from_radial(scalar, magnitude=1.0) scaled_vector = abs(scalar) * expected_vector # Act result = scaled_vector.unit # Assert assert result == expected_vector
def assignment(self): varLst = [] while self.isAssignment(): varLst.append(self.match().value) self.match(ASSIGN) self.sentenceValue() sym0 = self.getSymbol(varLst[0]) lastLevel = abs(self.level - sym0.level) lastAddr = sym0.addr self.genIns('STO', lastLevel, sym0.addr) for var in varLst[1:]: sym = self.getSymbol(var) if sym.type == 'CONST': raise Exception( '[Error]: Const "{}" can\'t be reassigned'.format( sym.name)) self.genIns('LOD', lastLevel, lastAddr) lastLevel = abs(self.level - sym.level) lastAddr = sym.addr self.genIns('STO', lastLevel, sym.addr)
def test_nintegrate(): from operator import abs # workaround abs / sympy.abs conflict Float.store() Float.setdps(20) pi_ = pi_float() assert nintegrate(lambda x: sin(x), 0, pi_).ae(2) assert nintegrate(lambda x: abs(sin(x)), 0, 10*pi_).ae(20) assert nintegrate(lambda x: sin(x), 0, 10*pi_).ae(0) assert nintegrate(lambda x: 4/(1+x**2), 0, 1).ae(pi_) assert nintegrate(lambda x: 4*sqrt(1-x**2), 0, 1).ae(pi_) Float.revert()
def test_decimal(self): self.assertEquals(-track(Decimal(5)), -5) self.assertEquals((-track(Decimal(5))).operations, neg(5)) self.assertEquals(operator.abs(track(Decimal(-5))).operations, abs(-5)) result = binary_op(Decimal, operator.mul, mul, 5, 3) self.assertEquals(result, 15) self.assertEquals(result.operations, mul(5, 3)) result = binary_op(Decimal, operator.add, add, result, result) self.assertEquals(result.operations, add(mul(5, 3), mul(5, 3)))
def funcall(self): name = self.match().value sym = self.getSymbol(name) saved = self.curClosure self.curClosure = sym.closure n2 = self.real_arg_list() self.curClosure = saved if sym.argNum != n2: self.errorArg(sym.argNum, n2) self.genIns('CAL', abs(self.level - sym.level), sym.value) self.genIns('INT', 1, n2) self.genIns('PUSH', 0, 0)
def swap_diff(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths. """ # BEGIN PROBLEM 6 if start == "" or goal == "": return abs(len(start) - len(goal)) elif start[0] != goal[0]: return 1 + swap_diff(start[1:], goal[1:], limit) else: return swap_diff(start[1:], goal[1:], limit)
def free_bacon(score): """Return the points scored from rolling 0 dice (Free Bacon). score: The opponent's current score. """ assert score < 100, 'The game should be over.' # BEGIN PROBLEM 2 "*** YOUR CODE HERE ***" n, a, b = 0, 0, 0 a = score // 10 b = score % 10 n = 2 + abs(a - b) return n
def generate_beenline_trace_between_two_point(point_a, point_b, radio=0.1): x1, y1 = point_a x2, y2 = point_b dx, dy = x2 - x1, y2 - y1 abs_x, abs_y = operator.abs(dx), operator.abs(dy) slope = dy / dx get_ty = lambda tx: (tx - x1) * slope + y1 ox, oy = tuple( map(lambda t: operator.add if t > 0 else operator.sub, (dx, dy))) base_step_x = abs_x // radio or 5 step_x_rng = base_step_x // 2 or 2 get_val = lambda x, y: random.randint(int(x) - y, int(x) + y) sx = 0 lx = x1 trace_list = list() # first point trace_list.append([x1, y1, int(get_timestamp())]) while True: time.sleep(random.randint(15, 40) / 1000) step_x = get_val(base_step_x, step_x_rng) tx = ox(lx, step_x) ty = get_ty(tx) ts = int(get_timestamp()) x = get_val(tx, 5) y = get_val(ty, 5) trace_list.append([x, y, ts]) sx += step_x lx = x if abs_x - sx <= base_step_x: break # last point trace_list.append([x2, y2, int(get_timestamp())]) return trace_list
def item(self): if self.isType('NUM'): val = float(self.match().value) self.genIns('LIT', 0, val) # elif self.isType('STR'): # val = self.match().value # self.genIns('LIT',0.,val) elif self.isType('LEFT'): self.match() self.sentenceValue() self.match(RIGHT) elif self.isType('SUB'): self.match() self.item() self.genIns('OPR', 1, 'NEG') elif self.isType('ADD'): self.match() self.item() elif self.isType('BITNOT'): self.match() self.item() self.genIns('OPR', 1, 'BITNOT') elif self.isType('RANDOM'): self.match() self.match(LEFT) if self.isType('RIGHT'): self.genIns('LIT', 0, 1 << 16) else: self.expression() self.match(RIGHT) self.genIns('OPR', 1, 'RND') elif self.isType('NAME'): if self.tokens[self.pointer + 1] == LEFT: self.funcall() else: name = self.match().value if name == 'true': self.genIns('LIT', 0, True) elif name == 'false': self.genIns('LIT', 0, False) else: sym = self.getSymbol(name) if sym.type == 'CONST': self.genIns('LIT', 0, sym.value) else: self.genIns('LOD', abs(self.level - sym.level), sym.addr) else: self.errorExpect('a value')
def divisor_count(n): """Return the number of divisors of n. Reference: http://www.mayer.dial.pipex.com/maths/formulae.htm >>> from sympy import divisor_count >>> divisor_count(6) 4 """ n = abs(n) if n == 0: return 0 return Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
def abs(a: protocols.SupportsAbs[A]) -> A: """ Return builtin `abs(a)`, for _a_. Example: >>> abs(-2) 2 Args: a: element of abs expression Return: b added to a """ return operator.abs(a)
def divisor_count(n): """Return the number of divisors of n. Reference: http://www.mayer.dial.pipex.com/maths/formulae.htm >>> from sympy import divisor_count >>> divisor_count(6) 4 """ n = abs(n) if n == 0: return 0 return Mul(*[v+1 for k, v in factorint(n).items() if k > 1])
def warning(list_map): listmap = [] for iterator in range(1, len(list_map)): listmap.append( operator.abs(list_map[iterator] - list_map[iterator - 1])) if len(listmap) == 1: rec_gcd = listmap[0] else: rec_gcd = reduce(lambda x, y: fractions.gcd(x, y), listmap) term = min(list_map) if term % rec_gcd == 0: retval = 0 elif term <= rec_gcd: retval = rec_gcd - term else: retval = (rec_gcd - (term % rec_gcd)) return retval
def ConvertToThreeCoulmnsInput(inputfilename, outputfilename='', outputfilepath=''): if (outputfilename == ''): outputfilename, ex = os.path.splitext(inputfilename) outputfilename = outputfilename + "_converted.csv" outputfilename = outputfilepath + outputfilename print("Converting input file " + inputfilename + " to intermediate three columns input file " + outputfilename + " in path " + outputfilepath + " ...") # open output file with open(outputfilename, 'wb') as outputFile: outputFileWriter = csv.writer(outputFile, delimiter="\t") # open input file with open(inputfilename) as inputFile: inputFileReader = csv.reader(inputFile, delimiter=',') # skip all rows that contain comments and begin with '%' at the beginning of the file x = next(inputFileReader) while (x[0].startswith("%")): x = next(inputFileReader) print("Skipping comments in header...") # skip the header for further processing, but write it into the output file outputFileWriter.writerow([x[1], x[3], x[6]]) for row in inputFileReader: # skip eventual comment lines that are contained inside the csv file if not row[0].startswith("%"): # perform data cleaning upon special characters # - replace any eventual " in the term_ID row[1] = row[1].replace("\"", "") # - convert log10pvalues to absolute values row[3] = abs(float(row[3])) # - replace any eventual " in the representative row[6] = row[6].replace("\"", "") # write the final output file outputFileWriter.writerow([row[1], row[3], row[6]]) inputFile.close() outputFile.close() print("Input file " + inputfilename + " cleaned and converted to tab deliminated file " + outputfilename + " in path " + outputfilepath + " ...")
def test_normal(): Float.store() Float.setdps(20) N = Normal(0, 1) assert N.mean == 0 assert N.variance == 1 assert N.probability(-1, 1) == erf(1/sqrt(2)) assert N.probability(-1, 0) == erf(1/sqrt(2))/2 N = Normal(2, 4) assert N.mean == 2 assert N.variance == 16 assert N.confidence(1) == (-oo, oo) assert N.probability(1, 3) == erf(1/sqrt(32)) for p in [0.1, 0.3, 0.7, 0.9, 0.995]: a, b = N.confidence(p) assert operator.abs(float(N.probability(a, b).evalf()) - p) < 1e-10 Float.revert()
def divisors(n, generator=False): r""" Return all divisors of n sorted from 1..n by default. If generator is True an unordered generator is returned. The number of divisors of n can be quite large if there are many prime factors (counting repeated factors). If only the number of factors is desired use divisor_count(n). Examples ======== >>> from sympy import divisors, divisor_count >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> divisor_count(24) 8 >>> list(divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] This is a slightly modified version of Tim Peters referenced at: http://stackoverflow.com/questions/1010381/python-factorization See Also ======== primefactors, factorint, divisor_count """ n = abs(n) if isprime(n): return [1, n] elif n == 1: return [1] elif n == 0: return [] else: rv = _divisors(n) if not generator: return sorted(rv) return rv
def new_warning_date(event_list): #event_list.sort(reverse=True) eventmap = [] for counter in range(1, len(event_list)): eventmap.append( operator.abs(event_list[counter] - event_list[counter - 1])) #print eventmap if len(eventmap) == 1: max_gcd = eventmap[0] else: max_gcd = reduce(lambda x, y: gcd(x, y), eventmap) #print max_gcd term = min(event_list) if term <= max_gcd: additive = max_gcd - term elif term % max_gcd == 0: additive = term % max_gcd else: additive = (max_gcd - (term % max_gcd)) return additive
def ptLine(self, pt, lnPt1, lnPt2): #point and domain value of closest point along straight line #pt references existing point reference #lnPt1 denotes the starting point of the line #lnPt2 denotes the ending point of the line pt = self.ptCheck(pt) lnPt1 = self.ptCheck(lnPt1) lnPt2 = self.ptCheck(lnPt2) if self.dist(lnPt1, lnPt2) < 0.00005: print "Two Points of line are both same value, cannot compute" print lnPt1, lnPt2 exit() #determine point position v1 = self.subUnit(lnPt1, lnPt2) qx = lnPt1[0] - pt[0] qy = lnPt1[1] - pt[1] qz = lnPt1[2] - pt[2] top = qx * v1[0] + qy * v1[1] + qz * v1[2] bot = v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] division = top / bot position = self.add(lnPt1, self.mult(v1, -division)) #determine from domain of from lnPt1. #0 is closest to lnPt1, 1 is closest to lnPt2 v2 = self.sub(lnPt1, position) lnPtDist = self.dist(lnPt1, lnPt2) ptDist = self.dist(lnPt1, position) if op.abs(self.vecDist(v2)) < 0.001: return (position, 0) else: quotient = self.dot(self.vecUnit(v2), self.vecUnit(v1)) * ptDist / lnPtDist #returns the position, and domain value return (position, quotient)
def test_normal(): dps, mp.dps = mp.dps, 20 N = Normal(0, 1) assert N.mean == 0 assert N.variance == 1 assert N.probability(-1, 1) == erf(1/sqrt(2)) assert N.probability(-1, 0) == erf(1/sqrt(2))/2 N = Normal(2, 4) assert N.mean == 2 assert N.variance == 16 assert N.confidence(1) == (-oo, oo) assert N.probability(1, 3) == erf(1/sqrt(32)) assert N.pdf(1).evalf() == (exp(Rational(-1,32)) / (4*sqrt(2*pi))).evalf() for p in [0.1, 0.3, 0.7, 0.9, 0.995]: a, b = N.confidence(p) assert operator.abs(float(N.probability(a, b).evalf()) - p) < 1e-10 N = Normal(0, 2/sqrt(2*pi)) assert N.pdf(0) == Rational(1,2) mp.dps = dps
def do_move(particles): min_distance = 999999 min_particle = -1 positions = {} for key in particles: p = particles[key] pos = p["pos"] vel = p["vel"] acc = p["acc"] vel = tuple(map(add, vel, acc)) pos = tuple(map(add, pos, vel)) p["pos"] = pos p["vel"] = vel # Calculate the haversine distance. new_dist = sum(abs(x) for x in pos) if new_dist < min_distance: min_distance = new_dist min_particle = key p["dist"] = new_dist if p["pos"] in positions: positions[p["pos"]].append(key) else: positions[p["pos"]] = [key] for pos_key in positions: pos = positions[pos_key] if len(pos) > 1: for key in pos: del particles[key] return len(particles)
def run301_03(): """ arithmetic ops :return: """ a = -1 b = 5.0 c = 2 d = 6 print('a =', a) print('b =', b) print('c =', c) print('d =', d) print('\nPositive/Negative:') print('abs(a):', abs(a)) print('neg(a):', neg(a)) print('neg(b):', neg(b)) print('pos(a):', pos(a)) print('pos(b):', pos(b)) print('\nArithmetic:') print('add(a, b) :', add(a, b)) print('floordiv(a, b):', floordiv(a, b)) # for py2 print('floordiv(d, c):', floordiv(d, c)) # for py2 print('mod(a, b) :', mod(a, b)) print('mul(a, b) :', mul(a, b)) print('pow(c, d) :', pow(c, d)) print('sub(b, a) :', sub(b, a)) print('truediv(a, b) :', truediv(a, b)) print('truediv(d, c) :', truediv(d, c)) print('\nBitwise:') print('and_(c, d) :', and_(c, d)) print('invert(c) :', invert(c)) # ~c print('lshift(c, d):', lshift(c, d)) # c << d print('or_(c, d) :', or_(c, d)) print('rshift(d, c):', rshift(d, c)) # d >> c print('xor(c, d) :', xor(c, d)) # 不同得1 ^
def calc_x_y(get_y, x_y, tv, rng_x, opt, step=0.005): error, rx, ry = inf, 0, 0 min_x, max_x = rng_x current_x = min_x if opt == operator.add else max_x while True: x = opt(current_x, step) y = get_y(x) ret = x_y(x=x, y=y) ce = operator.abs(ret - tv) if ce < error: rx = x ry = y error = ce if x >= max_x or x <= min_x: break current_x = x return rx, ry
def test_normal(): dps, mp.dps = mp.dps, 20 N = Normal(0, 1) assert N.mean == 0 assert N.variance == 1 assert N.probability(-1, 1) == erf(1 / sqrt(2)) assert N.probability(-1, 0) == erf(1 / sqrt(2)) / 2 N = Normal(2, 4) assert N.mean == 2 assert N.variance == 16 assert N.confidence(1) == (-oo, oo) assert N.probability(1, 3) == erf(1 / sqrt(32)) assert N.pdf(1).evalf() == (exp(Rational(-1, 32)) / (4 * sqrt(2 * pi))).evalf() for p in [0.1, 0.3, 0.7, 0.9, 0.995]: a, b = N.confidence(p) assert abs(float(N.probability(a, b).evalf()) - p) < 1e-10 N = Normal(0, 2 / sqrt(2 * pi)) assert N.pdf(0) == Rational(1, 2) mp.dps = dps
def operator_arithmetic(): """ arithmetic, math +, -, |a| +, -, *, //, /, %, pow &, |, ^, ~, <<, >> """ a, b, c, d = -1, 5.0, 2, 6 print('a =', a) print('b =', b) print('c =', c) print('d =', d) print('\nPositive/Negative:') print('abs(a):', operator.abs(a)) print('neg(a):', operator.neg(a)) print('neg(b):', operator.neg(b)) print('pos(a):', operator.pos(a)) print('pos(b):', operator.pos(b)) print('\nArithmetic:') print('add(a, b) :', operator.add(a, b)) print('sub(b, a) :', operator.sub(b, a)) print('mul(a, b) :', operator.mul(a, b)) print('truediv(a, b) :', operator.truediv(a, b)) print('truediv(d, c) :', operator.truediv(d, c)) print('floordiv(a, b) :', operator.floordiv(a, b)) print('pow(c, d) :', operator.pow(c, d)) print('mod(a, b) :', operator.mod(a, b)) print('\nBitwise:') print('and_(c, d) :', operator.and_(c, d)) # c & d print('or_(c, d) :', operator.or_(c, d)) # c | d print('invert(c) :', operator.invert(c)) # two's complement. ~c = -c - 1 print('xor(c, d) :', operator.xor(c, d)) # a ^ b print('lshift(c, d) :', operator.lshift(c, d)) # d << c print('rshift(d, c) :', operator.rshift(d, c)) # d >> c
def __abs__(self): return NonStandardInteger(operator.abs(self.val))
def perfect_power(n, candidates=None, big=True, factor=True): """ Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a perfect power; otherwise return ``False``. By default, the base is recursively decomposed and the exponents collected so the largest possible ``e`` is sought. If ``big=False`` then the smallest possible ``e`` (thus prime) will be chosen. If ``candidates`` for exponents are given, they are assumed to be sorted and the first one that is larger than the computed maximum will signal failure for the routine. If ``factor=True`` then simultaneous factorization of n is attempted since finding a factor indicates the only possible root for n. This is True by default since only a few small factors will be tested in the course of searching for the perfect power. Examples ======== >>> from sympy import perfect_power >>> perfect_power(16) (2, 4) >>> perfect_power(16, big = False) (4, 2) """ n = int(n) if n < 3: return False logn = math.log(n, 2) max_possible = int(logn) + 2 # only check values less than this not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8 if not candidates: candidates = primerange(2 + not_square, max_possible) afactor = 2 + n % 2 for e in candidates: if e < 3: if e == 1 or e == 2 and not_square: continue if e > max_possible: return False # see if there is a factor present if factor: if n % afactor == 0: # find what the potential power is if afactor == 2: e = trailing(n) else: e = multiplicity(afactor, n) # if it's a trivial power we are done if e == 1: return False # maybe the bth root of n is exact r, exact = integer_nthroot(n, e) if not exact: # then remove this factor and check to see if # any of e's factors are a common exponent; if # not then it's not a perfect power n //= afactor ** e m = perfect_power(n, candidates=primefactors(e), big=big) if m is False: return False else: r, m = m # adjust the two exponents so the bases can # be combined g = igcd(m, e) if g == 1: return False m //= g e //= g r, e = r ** m * afactor ** e, g if not big: e0 = primefactors(e) if len(e0) > 1 or e0[0] != e: e0 = e0[0] r, e = r ** (e // e0), e0 return r, e else: # get the next factor ready for the next pass through the loop afactor = nextprime(afactor) # Weed out downright impossible candidates if logn / e < 40: b = 2.0 ** (logn / e) if abs(int(b + 0.5) - b) > 0.01: continue # now see if the plausible e makes a perfect power r, exact = integer_nthroot(n, e) if exact: if big: m = perfect_power(r, big=big, factor=factor) if m is not False: r, e = m[0], e * m[1] return int(r), e else: return False
def test_abs(self): self.assertRaises(TypeError, operator.abs) self.assertRaises(TypeError, operator.abs, None) self.assertTrue(operator.abs(-1) == 1) self.assertTrue(operator.abs(1) == 1)
def abs(a): return operator.abs(a)
def __abs__(self): return Quaternion([operator.abs(c) for c in self]) def __neg__(self): return Quaternion([operator.neg(c) for c in self])
def __abs__ (self): return Vector([operator.abs(c) for c in self]) def __invert__(self): return Vector([operator.inv(c) for c in self])
def perfect_power(n, candidates=None, big=True, factor=True): """ Return ``(a, b)`` such that ``n`` == ``a**b`` if ``n`` is a perfect power; otherwise return ``None``. By default, the base is recursively decomposed and the exponents collected so the largest possible ``b`` is sought. If ``big=False`` then the smallest possible ``b`` (thus prime) will be chosen. If ``candidates`` are given, they are assumed to be sorted and the first one that is larger than the computed maximum will signal failure for the routine. If ``factor=True`` then simultaneous factorization of n is attempted since finding a factor indicates the only possible root for n. """ n = int(n) if n < 3: return None logn = math.log(n, 2) max_possible = int(logn) + 2 # only check values less than this not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8 if not candidates: candidates = primerange(2 + not_square, max_possible) afactor = 2 + n % 2 for b in candidates: if b < 3: if b == 1 or b == 2 and not_square: continue if b > max_possible: return # see if there is a factor present if factor: if n % afactor == 0: # find what the potential power is if afactor == 2: b = trailing(n) else: b = multiplicity(afactor, n) # if it's a trivial power we are done if b == 1: return # maybe the bth root of n is exact r, exact = integer_nthroot(n, b) if not exact: # then remove this factor and check to see if # any of b's factors are a common exponent; if # not then it's not a perfect power n //= afactor**b m = perfect_power(n, candidates=primefactors(b), big=big) if not m: return else: r, m = m # adjust the two exponents so the bases can # be combined g = igcd(m, b) m //= g b //= g r, b = r**m*afactor**b, g if not big: b0 = primefactors(b) if len(b0) > 1 or b0[0] != b: b0 = b0[0] r, b = r**(b//b0), b0 return r, b else: # get the next factor ready for the next pass through the loop afactor = nextprime(afactor) # Weed out downright impossible candidates if logn/b < 40: a = 2.0**(logn/b) if abs(int(a + 0.5) - a) > 0.01: continue # now see if the plausible b makes a perfect power r, exact = integer_nthroot(n, b) if exact: if big: m = perfect_power(r, big=big, factor=factor) if m: r, b = m[0], b*m[1] return int(r), b
def test_abs(self): self.failUnless(operator.abs(-1) == 1) self.failUnless(operator.abs(1) == 1)
old_ranks = ranks error = sc.accumulator(0) while (1): error.value = 0 print(">> Iteration : "+str(iteration)) # Calculates URL contributions to the rank of other URLs. contribs = links.join(ranks).flatMap( lambda url_urls_rank: computeContribs(url_urls_rank[1][0], url_urls_rank[1][1])) # Re-calculates URL ranks based on neighbor contributions. ranks = contribs.reduceByKey(add).mapValues(lambda rank: rank * ( 1 - damping ) + damping/total_links ) diff = old_ranks.join(ranks).mapValues(lambda rank: abs( rank[0] - rank[1] ) ) diff.foreach( lambda r: error.add(r[1] ) ) print(">> Error : "+str(error.value)) old_ranks = ranks if( error.value < 0.0001 ): break else: old_ranks = ranks iteration = iteration + 1 ranks = ranks.sortBy( lambda r: -r[1] )
def test_abs(self): self.failUnlessRaises(TypeError, operator.abs) self.failUnlessRaises(TypeError, operator.abs, None) self.failUnless(operator.abs(-1) == 1) self.failUnless(operator.abs(1) == 1)
def test_abs(self): self.failUnlessRaises(TypeError, operator.abs) self.failUnlessRaises(TypeError, operator.abs, None) self.assertEqual(operator.abs(-1), 1) self.assertEqual(operator.abs(1), 1)
def __abs__ (self): return Euler([operator.abs(c) for c in self]) def __neg__ (self): return Euler([operator.neg(c) for c in self])
def test_vec2d_magic_unary(): import operator assert tuple(operator.neg(cy.Vec2d(-1,1))) == pytest.approx((1,-1)) assert tuple(operator.pos(cy.Vec2d(-1,1))) == pytest.approx((-1,1)) assert tuple(operator.abs(cy.Vec2d(-1,1))) == pytest.approx((1,1))
def relcmp(a,b): from operator import abs # workaround for abs vs sympy.abs conflict return abs(a-b)/abs(a)
def test_unaryop(self): self.assertEquals(-track(5), -5) self.assertEquals((-track(5)).operations, neg(5)) self.assertEquals(operator.abs(track(-5)).operations, abs(-5))