本文整理汇总了Python中math.hypot函数的典型用法代码示例。如果您正苦于以下问题:Python hypot函数的具体用法?Python hypot怎么用?Python hypot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hypot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Execute
def Execute(self, device, rect):
if device.has_radial_gradient:
self.execute_radial(device, rect)
return
steps = device.gradient_steps
cx, cy = self.center
cx = cx * rect.right + (1 - cx) * rect.left
cy = cy * rect.top + (1 - cy) * rect.bottom
radius = max(
hypot(rect.left - cx, rect.top - cy),
hypot(rect.right - cx, rect.top - cy),
hypot(rect.right - cx, rect.bottom - cy),
hypot(rect.left - cx, rect.bottom - cy),
)
color = self.gradient.ColorAt
SetFillColor = device.SetFillColor
FillCircle = device.FillCircle
SetFillColor(color(0))
apply(device.FillRectangle, tuple(rect))
radius = radius * (1.0 - self.border)
dr = radius / steps
device.PushTrafo()
device.Translate(cx, cy)
center = NullPoint
for i in range(steps):
SetFillColor(color(float(i) / (steps - 1)))
FillCircle(center, radius)
radius = radius - dr
device.PopTrafo()
示例2: angle_between_points
def angle_between_points(pt1, pt2):
x1, y1 = pt1
x2, y2 = pt2
inner_product = x1 * x2 + y1 * y2
len1 = math.hypot(x1, y1)
len2 = math.hypot(x2, y2)
return math.acos(inner_product / (len1 * len2))
示例3: getInit
def getInit(p, q, P, Q):
seq = range(0, len(p)) # Create index
seq.append(seq.pop(0))
index = zip(range(0, len(p)), seq)
# Convert input parameters to arrays
p, q, P, Q = tuple(map(lambda x: np.array(x), [p, q, P, Q]))
# Get mean value of scale factrs as initial parameter of Sigma
Sigma = map(
lambda i: hypot(
p[i[1]] - p[i[0]],
q[i[1]] - q[i[0]]) / hypot(
P[i[1]] - P[i[0]],
Q[i[1]] - Q[i[0]]),
index)
Sigma0 = sum(Sigma) / len(p)
# Get mean rotate angle as initial parameter of theta
theta = map(
lambda i: atan2(
Q[i[1]] - Q[i[0]],
P[i[1]] - P[i[0]]) - atan2(
q[i[1]] - q[i[0]],
p[i[1]] - p[i[0]]),
index)
theta0 = sum(theta) / len(p)
# Compute initial horizontal and vertical translation
tp0 = (p - Sigma0 * (P * cos(theta0) + Q * sin(theta0))).mean()
tq0 = (q - Sigma0 * (P * -sin(theta0) + Q * cos(theta0))).mean()
return Sigma0, theta0, tp0, tq0
示例4: bounding_index
def bounding_index(coords):
min_x = 100000 # start with something much higher than expected min
min_y = 100000
max_x = -100000 # start with something much lower than expected max
max_y = -100000
for item in coords:
if item[0] < min_x:
min_x = item[0]
if item[0] > max_x:
max_x = item[0]
if item[1] < min_y:
min_y = item[1]
if item[1] > max_y:
max_y = item[1]
Nedges = len(coords)-1
length = []
for i in xrange(Nedges):
ax, ay = coords[i]
bx, by = coords[i+1]
#print ax,ay
length.append(math.hypot(bx-ax, by-ay))
#print length
peri_poly = np.sum(length)
peri_rect =2*(math.hypot(min_x - max_x, min_y - min_y) + math.hypot(max_x - max_x, min_y - max_y))
#print "peri_poly",peri_poly
#print "peri_rect",peri_rect
return peri_poly/peri_rect
示例5: vectorAngle
def vectorAngle(u,v):
d = hypot(*u)*hypot(*v)
c = (u[0]*v[0]+u[1]*v[1])/d
if c<-1: c = -1
elif c>1: c = 1
s = u[0]*v[1]-u[1]*v[0]
return degrees(copysign(acos(c),s))
示例6: computePupil
def computePupil(self):
a = self.get_allocation()
if self.x is None or self.y is None:
# look ahead, but not *directly* in the middle
if a.x + a.width/2 < self.parent.get_allocation().width/2:
cx = a.width * 0.6
else:
cx = a.width * 0.4
return cx, a.height * 0.6
EYE_X, EYE_Y = self.translate_coordinates(
self.get_toplevel(), a.width/2, a.height/2)
EYE_HWIDTH = a.width
EYE_HHEIGHT = a.height
BALL_DIST = EYE_HWIDTH/4
dx = self.x - EYE_X
dy = self.y - EYE_Y
if dx or dy:
angle = math.atan2(dy, dx)
cosa = math.cos(angle)
sina = math.sin(angle)
h = math.hypot(EYE_HHEIGHT * cosa, EYE_HWIDTH * sina)
x = (EYE_HWIDTH * EYE_HHEIGHT) * cosa / h
y = (EYE_HWIDTH * EYE_HHEIGHT) * sina / h
dist = BALL_DIST * math.hypot(x, y)
if dist < math.hypot(dx, dy):
dx = dist * cosa
dy = dist * sina
return a.width/2 + dx, a.height/2 + dy
示例7: test_math_functions
def test_math_functions(self):
df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF()
from pyspark.sql import functions
import math
def get_values(l):
return [j[0] for j in l]
def assert_close(a, b):
c = get_values(b)
diff = [abs(v - c[k]) < 1e-6 for k, v in enumerate(a)]
return sum(diff) == len(a)
assert_close([math.cos(i) for i in range(10)],
df.select(functions.cos(df.a)).collect())
assert_close([math.cos(i) for i in range(10)],
df.select(functions.cos("a")).collect())
assert_close([math.sin(i) for i in range(10)],
df.select(functions.sin(df.a)).collect())
assert_close([math.sin(i) for i in range(10)],
df.select(functions.sin(df['a'])).collect())
assert_close([math.pow(i, 2 * i) for i in range(10)],
df.select(functions.pow(df.a, df.b)).collect())
assert_close([math.pow(i, 2) for i in range(10)],
df.select(functions.pow(df.a, 2)).collect())
assert_close([math.pow(i, 2) for i in range(10)],
df.select(functions.pow(df.a, 2.0)).collect())
assert_close([math.hypot(i, 2 * i) for i in range(10)],
df.select(functions.hypot(df.a, df.b)).collect())
assert_close([math.hypot(i, 2 * i) for i in range(10)],
df.select(functions.hypot("a", u"b")).collect())
assert_close([math.hypot(i, 2) for i in range(10)],
df.select(functions.hypot("a", 2)).collect())
assert_close([math.hypot(i, 2) for i in range(10)],
df.select(functions.hypot(df.a, 2)).collect())
示例8: newPosition
def newPosition(avgError):
dock = [0,300]
xmin = 5
xmax = xmin+5 + ((1000-xmin-5)*(1-avgError))
ymid = 300
yrange = 295*(1-avgError)
x = random.randrange(int(xmin), int(xmax))
y = random.randrange(int(ymid - 5 - yrange), int(ymid + 5 + yrange))
goalAngle = math.atan2((dock[1]-y),(dock[0]-x))
if goalAngle < 0:
goalAngle += 2*pi
goalAngle = math.degrees(goalAngle)
nDist = math.hypot((x-dock[0]),(y-dock[1]))/(math.hypot(1000, 300))
ttrange = 80*(1-avgError)*(nDist)
tt = math.radians(random.randrange(int(goalAngle - 5 - ttrange), int(goalAngle + 5 + ttrange)))
if tt > 2*pi:
tt -= 2*pi
if tt < 0:
tt += 2*pi
tcrange = int(60*(1-avgError)*nDist)
tc = math.radians(random.randrange((- 5 - tcrange), (5 + tcrange)))
tc += math.radians(70)
print(x, y, tt, tc)
state = [x/1000, y/600, tt/(2*pi), tc/(math.radians(140))]
return state
示例9: closestTarget
def closestTarget(self, type, x, y):
minimum_magnitude = 10
if self.scaleImage():
xscale, yscale = self.getScale()
minimum_magnitude /= xscale
closest_target = None
if type is not None:
for target in self.targets[type]:
magnitude = math.hypot(x - target.x, y - target.y)
if magnitude < minimum_magnitude:
minimum_magnitude = magnitude
closest_target = target
if closest_target is None:
for key in self.reverseorder:
if key == type:
continue
for target in self.targets[key]:
magnitude = math.hypot(x - target.x, y - target.y)
if magnitude < minimum_magnitude:
minimum_magnitude = magnitude
closest_target = target
if closest_target is not None:
break
return closest_target
示例10: getPointBetweenBallAndGoal
def getPointBetweenBallAndGoal(self,dist_from_goal):
'''returns defensive position between ball (x,y) and goal (x,y)
at <dist_from_ball> centimeters away from ball'''
leftPostToBall = hypot(Constants.LANDMARK_MY_GOAL_LEFT_POST_X -
self.brain.ball.x,
Constants.LANDMARK_MY_GOAL_LEFT_POST_Y -
self.brain.ball.y)
rightPostToBall = hypot(Constants.LANDMARK_MY_GOAL_RIGHT_POST_X -
self.brain.ball.x,
Constants.LANDMARK_MY_GOAL_RIGHT_POST_Y -
self.brain.ball.y)
goalLineIntersectionX = Constants.LANDMARK_MY_GOAL_LEFT_POST_X +\
(leftPostToBall*Constants.GOAL_WIDTH)/(leftPostToBall+rightPostToBall)
ballToInterceptDist = hypot(self.brain.ball.y -
Constants.LANDMARK_MY_GOAL_LEFT_POST_Y,
self.brain.ball.x - goalLineIntersectionX)
pos_x = ((dist_from_goal / ballToInterceptDist)*
(self.brain.ball.x -goalLineIntersectionX) +
goalLineIntersectionX)
pos_y = ((dist_from_goal / ballToInterceptDist)*
(self.brain.ball.y -
Constants.LANDMARK_MY_GOAL_LEFT_POST_Y) +
Constants.LANDMARK_MY_GOAL_LEFT_POST_Y)
return pos_x,pos_y
示例11: estimate
def estimate(self):
"""
Estimate the additional drift since previous acquisition+estimation.
Note: It should be only called once after every acquisition.
To read the value again, use .orig_drift.
return (float, float): estimated current drift in X/Y SEM px
"""
# Calculate the drift between the last two frames and
# between the last and first frame
if len(self.raw) > 1:
# Note: prev_drift and orig_drift, don't represent exactly the same
# value as the previous image also had drifted. So we need to
# include also the drift of the previous image.
# Also, CalculateDrift return the shift in image pixels, which is
# different (usually bigger) from the SEM px.
prev_drift = CalculateDrift(self.raw[-2], self.raw[-1], 10)
prev_drift = (prev_drift[0] * self._scale[0] + self.orig_drift[0],
prev_drift[1] * self._scale[1] + self.orig_drift[1])
orig_drift = CalculateDrift(self.raw[0], self.raw[-1], 10)
self.orig_drift = (orig_drift[0] * self._scale[0],
orig_drift[1] * self._scale[1])
logging.debug("Current drift: %s", self.orig_drift)
logging.debug("Previous frame diff: %s", prev_drift)
if (abs(self.orig_drift[0] - prev_drift[0]) > 5 or
abs(self.orig_drift[1] - prev_drift[1]) > 5):
logging.warning("Drift cannot be measured precisely, "
"hesitating between %s and %s px",
self.orig_drift, prev_drift)
# Update max_drift
if math.hypot(*self.orig_drift) > math.hypot(*self.max_drift):
self.max_drift = self.orig_drift
return self.orig_drift
示例12: segment_sp
def segment_sp(sp):
bks = set()
# direction changes
xsg = 0
ysg = 0
for i in range(2 * len(sp)):
imod = i % len(sp)
xsg1 = sp[imod][-1][0] - sp[imod][0][0]
ysg1 = sp[imod][-1][1] - sp[imod][0][1]
if xsg * xsg1 < 0 or ysg * ysg1 < 0:
bks.add(imod)
xsg = xsg1
ysg = ysg1
else:
if xsg == 0: xsg = xsg1
if ysg == 0: ysg = ysg1
# angle breaks
for i in range(len(sp)):
dx0 = sp[i-1][-1][0] - sp[i-1][-2][0]
dy0 = sp[i-1][-1][1] - sp[i-1][-2][1]
dx1 = sp[i][1][0] - sp[i][0][0]
dy1 = sp[i][1][1] - sp[i][0][1]
bend = dx1 * dy0 - dx0 * dy1
if (dx0 == 0 and dy0 == 0) or (dx1 == 0 and dy1 == 0):
bks.add(i)
else:
bend = bend / (math.hypot(dx0, dy0) * math.hypot(dx1, dy1))
# for small angles, bend is in units of radians
if abs(bend) > 0.02:
bks.add(i)
return sorted(bks)
示例13: get_trans_power
def get_trans_power(n, control):
"""Takes the motor number and returns the power it should output for
translational motion, from -1 to 1.
Raises a ValueError if the motor number is unrecognized."""
# these motors don't have an effect on translational speed
if n == MOTOR.FR_VT or n == MOTOR.BA_VT:
return 0;
x = control.trans_x_value();
y = control.trans_y_value();
if x == 0 and y == 0:
return 0;
m1 = .5 * x + y / (2 * math.sqrt(3));
m2 = -.5 * x + y / (2 * math.sqrt(3));
m1_norm = m1 / abs(max(m1, m2)) * min(math.hypot(x, y), 1);
m2_norm = m2 / abs(max(m1, m2)) * min(math.hypot(x, y), 1);
if n == MOTOR.FR_LF:
return -1 * m1_norm;
if n == MOTOR.FR_RT:
return -1 * m2_norm;
if n == MOTOR.BA_RT:
return m1_norm;
if n == MOTOR.BA_LF:
return m2_norm;
raise ValueError("get_trans_power: Illegal motor number");
示例14: __init__
def __init__(self, s1, s2, l, st=None, lt=None, col=None, t=None, **kw):
super(Chamfer, self).__init__(s1, s2, st, lt, col, t, **kw)
_len = util.get_float(l)
if _len < 0.0:
raise ValueError, "Invalid chamfer length: %g" % _len
if _len > s1.length():
raise ValueError, "Chamfer is longer than first Segment."
if _len > s2.length():
raise ValueError, "Chamfer is longer than second Segment."
_xi, _yi = SegJoint.getIntersection(self)
# print "xi: %g; yi: %g" % (_xi, _yi)
_sp1, _sp2 = SegJoint.getMovingPoints(self)
_xp, _yp = _sp1.getCoords()
_sep = hypot((_yp - _yi), (_xp - _xi))
if _sep > (_len + 1e-10):
# print "sep: %g" % _sep
# print "xp: %g; yp: %g" % (_xp, _yp)
raise ValueError, "First segment too far from intersection point."
_xp, _yp = _sp2.getCoords()
_sep = hypot((_yp - _yi), (_xp - _xi))
if _sep > (_len + 1e-10):
# print "sep: %g" % _sep
# print "xp: %g; yp: %g" % (_xp, _yp)
raise ValueError, "Second segment too far from intersection point."
self.__length = _len
self.ignore('moved')
try:
self._moveSegmentPoints(_len)
finally:
self.receive('moved')
示例15: update
def update(self):
self.show(self.image,False)
#print 'time passed', time_passed
#This goes through the location of the ant when it stops to see if there is a collony there
if hypot ((self.int_pos[0]-self.int_target[0]),(self.int_pos[1]-self.int_target[1])) <=5:
for c in self.game.colony_list: # and if so runs that collonies collide code
if hypot((c.pos[0]-self.x),(c.pos[1]-self.y)) <= 20:
c.collide(self)
else:
self.die()
target_vector = sub(self.target, self.pos)
# a threshold to stop moving if the distance is to small.
# it prevents a 'flickering' between two points
if magnitude(target_vector) < 2:
return
# apply the ship's speed to the vector
move_vector = [c * self.speed for c in normalize(target_vector)]
# update position
self.x, self.y = add(self.pos, move_vector)
#print self.x, self.y
self.angle = degrees(atan2(self.t_y - self.y, self.t_x - self.x)) + 90 #calculate angle to target
self.show(self.image,True)