本文整理汇总了Python中math.hypot函数的典型用法代码示例。如果您正苦于以下问题:Python hypot函数的具体用法?Python hypot怎么用?Python hypot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hypot函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:moljac,项目名称:HolisticWare.Productivity.Xamarin.Mobile.Artwork,代码行数:29,代码来源:pattern.py
示例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))
开发者ID:RUAutonomous,项目名称:DataProcessing,代码行数:7,代码来源:geotag.py
示例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
开发者ID:otakusaikou,项目名称:2015-521-M7410,代码行数:33,代码来源:hw6.py
示例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
开发者ID:animeshh,项目名称:nuclei-analysis,代码行数:34,代码来源:analysis.py
示例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))
开发者ID:AndyKovv,项目名称:hostel,代码行数:7,代码来源:svglib.py
示例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
开发者ID:pmoleri,项目名称:memorize-accesible,代码行数:34,代码来源:eye.py
示例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())
开发者ID:apache,项目名称:spark,代码行数:34,代码来源:test_functions.py
示例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
开发者ID:NiklasMelton,项目名称:research_code,代码行数:28,代码来源:kinematics_test.py
示例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
开发者ID:spartango,项目名称:LeginonSpots,代码行数:29,代码来源:TargetPanel.py
示例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
开发者ID:Flavkupe,项目名称:tool,代码行数:31,代码来源:JTeam.py
示例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
开发者ID:ktsitsikas,项目名称:odemis,代码行数:35,代码来源:__init__.py
示例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)
开发者ID:roozbehp,项目名称:fontbakery,代码行数:34,代码来源:fontcrunch.py
示例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");
开发者ID:ryanedwincox,项目名称:Controller,代码行数:28,代码来源:MotorController.py
示例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')
开发者ID:chrisbura,项目名称:pythoncad-legacy-layertable,代码行数:30,代码来源:segjoint.py
示例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)
开发者ID:samsath,项目名称:Colonise,代码行数:29,代码来源:Tim's+main.py
示例16: fill_data
def fill_data(df, start_date, end_date, nan=True):
"""
Fill data in missing rows of *df* in the time interval
*start_date* to *end_date* (one minute sample period, closed on
the left and open on the right)). If *nan* will with not a
numbers, otherwise fill with 88888 (i.e., the missing value in
IAGA2002 data records). Return the tuple of the list of date/times
for each data record and the list of tuple values (containing the
N, E, Z, and F in [nT] in that order).
"""
data_map = {}
for row in df.itertuples():
N = row.N
E = row.E
Z = row.Z
F = math.hypot(math.hypot(N, E), Z)
data_map[row.Date_UTC] = (N, E, Z, F)
# fill missing records
filled_data = []
dts = list(PD.date_range(start=start_date, end=end_date, freq="min"))[:-1]
if nan:
fill_value = (float("nan"),) * 4
else:
fill_value = (88888,) * 4
missing_count = 0
for dt in dts:
if dt not in data_map:
missing_count += 1
filled_data.append(data_map.get(dt, fill_value))
if missing_count > 0:
logger.info("filled {} missing values".format(missing_count))
return dts, filled_data
开发者ID:butala,项目名称:pyrsss,代码行数:32,代码来源:sm2iaga.py
示例17: vector_abs
def vector_abs(*args):
if len(args) == 1:
point = args[0]
return math.hypot(point.x, point.y)
elif len(args) == 2:
x, y = args
return math.hypot(x, y)
开发者ID:ps-kostikov,项目名称:russianaicup2014,代码行数:7,代码来源:geometry.py
示例18: onCollision
def onCollision(self,_other):
Hitbox.onCollision(self, _other)
if 'AbstractFighter' in list(map(lambda x:x.__name__,_other.__class__.__bases__)) + [_other.__class__.__name__]:
if _other.lockHitbox(self):
if self.article is None:
self.owner.applyPushback(self.base_knockback/5.0, self.getTrajectory()+180, (self.damage / 3.0 + 3.0)*self.hitlag_multiplier)
x_diff = self.rect.centerx - _other.rect.centerx
y_diff = self.rect.centery - _other.rect.centery
x_vel = self.x_bias*self.owner.facing+self.x_draw*x_diff
y_vel = self.y_bias+self.y_draw*y_diff
self.owner.data_log.addToData('Damage Dealt',self.damage)
_other.applyKnockback(self.damage, math.hypot(x_vel,y_vel)*self.velocity_multiplier+self.base_knockback, self.knockback_growth, self.owner.getForwardWithOffset(self.owner.facing*(math.degrees(-math.atan2(y_vel,x_vel))+self.trajectory)), self.weight_influence, self.hitstun_multiplier, self.base_hitstun, self.hitlag_multiplier, self.ignore_armor)
else:
x_diff = self.article.rect.centerx - _other.rect.centerx
y_diff = self.article.rect.centery - _other.rect.centery
x_vel = self.x_bias*self.article.facing+self.x_draw*x_diff
y_vel = self.y_bias+self.y_draw*y_diff
self.owner.data_log.addToData('Damage Dealt',self.damage)
_other.applyKnockback(self.damage, math.hypot(x_vel,y_vel)*self.velocity_multiplier+self.base_knockback, self.knockback_growth, getForwardWithOffset(self.article.facing*(math.degrees(-math.atan2(y_vel,x_vel))+self.trajectory), self.article), self.weight_influence, self.hitstun_multiplier, self.base_hitstun, self.hitlag_multiplier, self.ignore_armor)
_other.trail_color = self.trail_color
offset = random.randrange(0, 359)
hit_intersection = self.rect.clip(_other.sprite.rect).center
hitlag = (self.damage/3.0+3.0)*self.hitlag_multiplier
from article import HitArticle
for i in range(int(hitlag)):
art = HitArticle(self.owner, hit_intersection, 0.5, offset+i*360/int(hitlag), 0.5*hitlag, .4, self.trail_color)
self.owner.articles.add(art)
Hitbox.onCollision(self, _other)
if self.article and hasattr(self.article, 'onCollision'):
self.article.onCollision(_other)
开发者ID:sylvanelite,项目名称:universalSmashSystem,代码行数:32,代码来源:hitbox.py
示例19: run
def run(self):
""" generate observetion list
:returns: list of observation dicts ordered by hz
"""
observations = []
for coo in self.coords:
if self.station_id == coo['id']:
#skip station
continue
obs = {}
d_north = coo['north'] - self.station_north
d_east = coo['east'] - self.station_east
d_elev = coo['elev'] - self.station_elev - self.station_ih
bearing = math.atan2(d_east, d_north)
dist = math.hypot(d_east, d_north)
zenith = math.atan2(dist, d_elev)
obs['id'] = coo['id']
obs['ih'] = self.station_ih
obs['hz'] = Angle(bearing).Positive()
obs['v'] = Angle(zenith).Positive()
obs['distance'] = math.hypot(dist, d_elev)
obs['code'] = 'ATR'
obs['faces'] = self.faces
if 'code' in coo and coo['code'] in modes1:
obs['code'] = coo['code']
observations.append(obs)
observations = sorted(observations, key = lambda a: a['hz'].GetAngle())
obs = {}
obs['station'] = self.station_id
obs['ih'] = self.station_ih
observations.insert(0, obs)
return observations
开发者ID:GEO-IASS,项目名称:ulyxes,代码行数:33,代码来源:filegen.py
示例20: calcCoordsAndDelay
def calcCoordsAndDelay(self, startCoords, endCoords):
veloX, veloY = (0, 0)
coordsAndDelay = []
xs, ys = startCoords
xe, ye = endCoords
totalDist = math.hypot(xs - xe, ys - ye)
self._windX = 0
self._windY = 0
while True:
veloX, veloY = self._calcVelocity(
(xs, ys), (xe, ye), veloX, veloY, totalDist)
xs += veloX
ys += veloY
w = round(
max(random.randint(0, max(0, round(100 / self.mouseSpeed) - 1)) * 6, 5) * 0.9)
coordsAndDelay.append((xs, ys, w))
if math.hypot(xs - xe, ys - ye) < 1:
break
if round(xe) != round(xs) or round(ye) != round(ys):
coordsAndDelay.append((round(xe), round(ye), 0))
return coordsAndDelay
开发者ID:jjvilm,项目名称:osrmacro,代码行数:28,代码来源:Mouse.py
注:本文中的math.hypot函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论