def setup_xy(self, p1_world, p2_world, p1_ucs, p2_ucs):
""" setup an UCS given by the points p1 and p2
only xy-plane, z' = z
"""
ucs_angle_to_x_axis = get_angle(p1_ucs, p2_ucs)
world_angle_to_x_axis = get_angle(p1_world, p2_world)
rotation = normalize_angle(world_angle_to_x_axis - ucs_angle_to_x_axis)
self._xaxis = (math.cos(rotation), math.sin(rotation), 0.)
self._yaxis = (math.cos(rotation + HALF_PI), math.sin(rotation + HALF_PI), 0.)
self._zaxis = (0., 0., 1.)
ucs_angle_to_x_axis = get_angle((0., 0.), p1_ucs)
world_angle_to_x_axis = rotation + ucs_angle_to_x_axis
distance_from_ucs_origin = math.hypot(p1_ucs[0], p1_ucs[1])
delta_x = distance_from_ucs_origin * math.cos(world_angle_to_x_axis)
delta_y = distance_from_ucs_origin * math.sin(world_angle_to_x_axis)
self._origin = (p1_world[0] - delta_x, p1_world[1] - delta_y, 0.)
python类hypot()的实例源码
def CursorClosestTo(verts, allowedError = 0.025):
ratioX, ratioY = ImageRatio()
#any length that is certantly not smaller than distance of the closest
min = 1000
minV = verts[0]
for v in verts:
if v is None: continue
for area in bpy.context.screen.areas:
if area.type == 'IMAGE_EDITOR':
loc = area.spaces[0].cursor_location
hyp = hypot(loc.x/ratioX -v.uv.x, loc.y/ratioY -v.uv.y)
if (hyp < min):
min = hyp
minV = v
if min is not 1000: return minV
return None
def placeLeak(self, leak):
tooClose = True
attempts = 0
while tooClose and attempts < self._MAX_TRIES:
attempts += 1
locator = self.locators[random.randint(0, len(self.locators) - 1)]
relative = self.getRelativePoint(self.board, Point3(locator.getX(), 0, locator.getZ()))
x = relative.getX()
z = relative.getZ()
tooClose = False
for otherLeak in self.activeLeaks:
dist = math.hypot(otherLeak.getX() - x, otherLeak.getZ() - z)
if dist < self._MIN_DIST:
tooClose = True
continue
for otherLeak in self.patchedLeaks:
dist = math.hypot(otherLeak.getX() - x, otherLeak.getZ() - z)
if dist < self._MIN_DIST:
tooClose = True
continue
leak.repositionTo(x, z)
def diversity(first_front, first, last):
"""Given a Pareto front `first_front` and the two extreme points of the
optimal Pareto front, this function returns a metric of the diversity
of the front as explained in the original NSGA-II article by K. Deb.
The smaller the value is, the better the front is.
"""
df = hypot(first_front[0].fitness.values[0] - first[0],
first_front[0].fitness.values[1] - first[1])
dl = hypot(first_front[-1].fitness.values[0] - last[0],
first_front[-1].fitness.values[1] - last[1])
dt = [hypot(first.fitness.values[0] - second.fitness.values[0],
first.fitness.values[1] - second.fitness.values[1])
for first, second in zip(first_front[:-1], first_front[1:])]
if len(first_front) == 1:
return df + dl
dm = sum(dt)/len(dt)
di = sum(abs(d_i - dm) for d_i in dt)
delta = (df + dl + di)/(df + dl + len(dt) * dm )
return delta
def find_retreat_positions(self):
total_num_position = 1
retreat_positions = []
current_segment = -1
offset_distance = 1
current_retrace_length = 0
while offset_distance < total_num_position + 1:
length = math.hypot(self.computed_path[current_segment][0] - self.computed_path[current_segment - 1][0],
self.computed_path[current_segment][1] - self.computed_path[current_segment - 1][1])
while offset_distance < current_retrace_length + length and offset_distance < total_num_position + 1:
proportion = (offset_distance - current_retrace_length) / length
new_position = list(self.computed_path[current_segment]
+ (np.array(self.computed_path[current_segment - 1])
- self.computed_path[current_segment]) * proportion)
retreat_positions.append(new_position)
offset_distance += 1
current_retrace_length += length
return retreat_positions
def test_hypo(points):
dfz = Defuzzer(ndigits=0)
dfz_points = [dfz.defuzz(pt) for pt in points]
# The output values should all be in the inputs.
assert all(pt in points for pt in dfz_points)
# No two unequal output values should be too close together.
if len(points) > 1:
for a, b in all_pairs(dfz_points):
if a == b:
continue
distance = math.hypot(a[0] - b[0], a[1] - b[1])
assert distance > .5
def distance(self, other):
"""Compute the distance from this Point to another Point."""
assert isinstance(other, Point)
x1, y1 = self
x2, y2 = other
return math.hypot(x2 - x1, y2 - y1)
def offset(self, distance):
"""Create another Line `distance` from this one."""
(x1, y1), (x2, y2) = self
dx = x2 - x1
dy = y2 - y1
hyp = math.hypot(dx, dy)
offx = dy / hyp * distance
offy = -dx / hyp * distance
return Line(Point(x1 + offx, y1 + offy), Point(x2 + offx, y2 + offy))
def __abs__(self): # ??
return math.hypot(self.x, self.y)
def __abs__(self): # ??
return math.hypot(self.x, self.y)
def __abs__(self): # ??
return math.hypot(self.x, self.y)
def _distance(p0, p1):
return math.hypot(p0[0] - p1[0], p0[1] - p1[1])
def dist(cls, p1, p2):
(x1, y1), (x2, y2) = p1, p2
return math.hypot(x1 - x2, y1 - y2)
def __init__(self, start, point=None, vector=None):
"Create a line or line segment"
self.pos = start
if point:
ux = point[0] - start[0]
uy = point[1] - start[1]
elif type(vector) in (int, float):
ux = 1
uy = vector
else: ux, uy = vector
self._size = abs(ux), abs(uy)
u = hypot(ux, uy)
self.length = u #if point else None
self.u = ux / u, uy / u
def ondraw(self):
# Calculate electric force
sk = self.sketch
dr = delta(self.pos, sk["blue"].pos)
r = hypot(*dr) / sk.scale / 100
F = delta(dr, mag = 8.99e-3 * sk.q1 * sk.q2 / (r * r))
# Add electric plus gravitational forces
F = F[0], F[1] + sk.mass * 9.81e-3
# Tangential acceleration
s = sk["string"]
u = s.u
t = 1 / sk.frameRate
F = (F[0] * u[1] - F[1] * u[0]) / (sk.mass / 1000) * (sk.scale / 100) / t ** 2
ax, ay = F * u[1], -F * u[0]
# Kinematics
v1x, v1y = tuple(0.95 * v for v in self.vel)
v2x = v1x + ax * t
v2y = v1y + ay * t
self.vel = v2x, v2y
x, y = self.pos
x += (v1x + v2x) * t / 2
y += (v1y + v2y) * t / 2
x, y = delta((x,y), s.pos, 20 * sk.scale)
self.pos = s.pos[0] + x, s.pos[1] + y
s.__init__(s.pos, self.pos)
# Protractor
if s.u[1] > 0:
a = round(2 * degrees(asin(s.u[0]))) / 2
a = "Angle = {:.1f}° ".format(abs(a))
else: a = "Angle = ? "
sk["angle"].config(data=a)
def checkFront(self):
"Update the front color sensor"
# Get sensor position
pos = delta(self.pos, vec2d(-self.radius, self.angle))
# Sensor distance to edge of sketch
sk = self.sketch
if sk.weight:
obj = sk
prox = _distToWall(pos, self.angle, self.sensorWidth, *sk.size)
else: obj = prox = None
# Find closest object within sensor width
u = vec2d(1, self.angle)
sw = self.sensorWidth * DEG
for gr in self.sensorObjects(sk):
if gr is not self and gr.avgColor and hasattr(gr, "rect"):
dr = delta(gr.rect.center, pos)
d = hypot(*dr)
r = gr.radius
if r >= d:
prox = 0
obj = gr
elif prox is None or d - r < prox:
minDot = cos(min(sw + asin(r/d), pi / 2))
x = (1 - sprod(u, dr) / d) / (1 - minDot)
if x < 1:
obj = gr
prox = (d - r) * (1 - x) + x * sqrt(d*d-r*r)
# Save data
self.closestObject = obj
c = rgba(sk.border if obj is sk
else obj.avgColor if obj else (0,0,0))
self.sensorFront = noise(divAlpha(c), self.sensorNoise, 255)
self.proximity = None if prox is None else round(prox)
def dist(p1, p2):
"Distance between two points"
return hypot(p2[0] - p1[0], p2[1] - p1[1])
def polar2d(vx, vy, deg=True):
"2D Cartesian to Polar conversion"
a = atan2(vy, vx)
return hypot(vx, vy), (a / DEG if deg else a)
def elasticCircles(mass1, mass2):
"Set final velocities for an elastic collision between two circles"
# Calculate the normal vector at contact point
x1, y1 = mass1.rect.center
x2, y2 = mass2.rect.center
nx = x2 - x1
ny = y2 - y1
r = hypot(nx, ny)
if r >= mass1.radius + mass2.radius or r == 0:
return # No contact!
nx /= r
ny /= r
# Calculate initial momenta
m1 = mass1.mass
m2 = mass2.mass
v1x, v1y = mass1.vel
v2x, v2y = mass2.vel
p1x = m1 * v1x
p1y = m1 * v1y
p2x = m2 * v2x
p2y = m2 * v2y
# Calculate impulse and final velocities
impulse = 2 * (m2 * (p1x * nx + p1y * ny) - m1 * (p2x * nx + p2y * ny)) / (m1 + m2)
if impulse > 0:
mass1.vel = (p1x - impulse * nx) / m1, (p1y - impulse * ny) / m1
mass2.vel = (p2x + impulse * nx) / m2, (p2y + impulse * ny) / m2
return True
def __abs__(self):
'Return the vector\'s magnitude.'
return _math.hypot(self.x, self.y)