Python math.hypot() Examples

The following are 30 code examples of math.hypot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source Project: renpy-shader   Author: bitsawer   File: geometry.py    License: MIT License 6 votes vote down vote up
def simplifyEdgePixels(pixels, minDistance):
    results = []

    i = 0
    while i < len(pixels):
        results.append((float(pixels[i][0]), float(pixels[i][1])))

        distance = 0
        i2 = i + 1
        while i2 < len(pixels):
            previous = (pixels[i2 - 1][0], pixels[i2 - 1][1])
            current = (pixels[i2][0], pixels[i2][1])
            distance += math.hypot(current[0] - previous[0], current[1] - previous[1])
            if distance > minDistance:
                break
            i2 += 1
        i = i2

    return results 
Example #2
Source Project: OctoPrint-ExcludeRegionPlugin   Author: bradcfisher   File: CircularRegion.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def containsRegion(self, otherRegion):
        """
        Check if another region is fully contained in this region.

        Returns
        -------
        True if the other region is fully contained inside this region, and False otherwise.
        """
        from octoprint_excluderegion.RectangularRegion import RectangularRegion

        if (isinstance(otherRegion, RectangularRegion)):
            return (
                self.containsPoint(otherRegion.x1, otherRegion.y1) and
                self.containsPoint(otherRegion.x2, otherRegion.y1) and
                self.containsPoint(otherRegion.x2, otherRegion.y2) and
                self.containsPoint(otherRegion.x1, otherRegion.y2)
            )
        elif (isinstance(otherRegion, CircularRegion)):
            dist = math.hypot(self.cx - otherRegion.cx, self.cy - otherRegion.cy) + otherRegion.r
            return (dist <= self.r)
        else:
            raise ValueError("unexpected type: {otherRegion}".format(otherRegion=otherRegion)) 
Example #3
Source Project: respeaker_python_library   Author: respeaker   File: fft.py    License: Apache License 2.0 6 votes vote down vote up
def dft(self, data, typecode='h'):
        if type(data) is str:
            a = array.array(typecode, data)
            for index, value in enumerate(a):
                self.real_input[index] = float(value)
        elif type(data) is array.array:
            for index, value in enumerate(data):
                self.real_input[index] = float(value)

        self.fftwf_execute(self.fftwf_plan)

        for i in range(len(self.amplitude)):
            self.amplitude[i] = math.hypot(self.complex_output[i * 2], self.complex_output[i * 2 + 1])
            # self.phase[i] = math.atan2(self.complex_output[i * 2 + 1], self.complex_output[i * 2])

        return self.amplitude  # , self.phase 
Example #4
Source Project: Robofont-scripts   Author: loicsander   File: glyphObjects.py    License: MIT License 6 votes vote down vote up
def constrainSegmentOffcurves(self, a1, h1, h2, a2):
        ax1, ay1 = a1
        hx1, hy1 = h1
        hx2, hy2 = h2
        ax2, ay2 = a2

        ix, iy = self.intersectLineLine(a1, h1, h2, a2)

        if (ix != None) and (iy != None):

            d1 = hypot(hx1-ax1, hy1-ay1)
            di1 = hypot(ix-ax1, iy-ay1)
            if d1 >= di1:
                t1 = atan2(hy1-ay1, hx1-ax1)
                hx1 = ax1 + 0.99*di1*cos(t1)
                hy1 = ay1 + 0.99*di1*sin(t1)

            d2 = hypot(hx2-ax2, hy2-ay2)
            di2 = hypot(ix-ax2, iy-ay2)
            if d2 >= di2:
                t2 = atan2(hy2-ay2, hx2-ax2)
                hx2 = ax2 + 0.99*di2*cos(t2)
                hy2 = ay2 + 0.99*di2*sin(t2)

        return (round(hx1), round(hy1)), (round(hx2), round(hy2)) 
Example #5
Source Project: xy   Author: fogleman   File: planner.py    License: MIT License 6 votes vote down vote up
def add_distances(self, indexes):
        n = len(self.distances)
        for i in indexes:
            if i < 0 or i >= n:
                continue
            j = i + 1
            if self.reverse[i]:
                x1, y1 = self.paths[i][0]
            else:
                x1, y1 = self.paths[i][-1]
            if self.reverse[j]:
                x2, y2 = self.paths[j][-1]
            else:
                x2, y2 = self.paths[j][0]
            self.distances[i] = hypot(x2 - x1, y2 - y1)
            self.total_distance += self.distances[i] 
Example #6
Source Project: pyx   Author: pyx-project   File: box.py    License: GNU General Public License v2.0 6 votes vote down vote up
def pointdistance_pt(self, x, y):
        result = None
        for p1, p2 in self.successivepoints():
            gx, gy = p2[0] - p1[0], p2[1] - p1[1]
            if gx * gx + gy * gy < 1e-10:
                dx, dy = p1[0] - x, p1[1] - y
            else:
                a = (gx * (x - p1[0]) + gy * (y - p1[1])) / (gx * gx + gy * gy)
                if a < 0:
                    dx, dy = p1[0] - x, p1[1] - y
                elif a > 1:
                    dx, dy = p2[0] - x, p2[1] - y
                else:
                    dx, dy = x - p1[0] - a * gx, y - p1[1] - a * gy
            new = math.hypot(dx, dy)
            if result is None or new < result:
                result = new
        return result 
Example #7
Source Project: pyx   Author: pyx-project   File: normpath.py    License: GNU General Public License v2.0 6 votes vote down vote up
def curvature_pt(self, params):
        result = []
        # see notes in rotation
        approxarclen = (math.hypot(self.x1_pt-self.x0_pt, self.y1_pt-self.y0_pt) +
                        math.hypot(self.x2_pt-self.x1_pt, self.y2_pt-self.y1_pt) +
                        math.hypot(self.x3_pt-self.x2_pt, self.y3_pt-self.y2_pt))
        for param in params:
            xdot = ( 3 * (1-param)*(1-param) * (-self.x0_pt + self.x1_pt) +
                     6 * (1-param)*param * (-self.x1_pt + self.x2_pt) +
                     3 * param*param * (-self.x2_pt + self.x3_pt) )
            ydot = ( 3 * (1-param)*(1-param) * (-self.y0_pt + self.y1_pt) +
                     6 * (1-param)*param * (-self.y1_pt + self.y2_pt) +
                     3 * param*param * (-self.y2_pt + self.y3_pt) )
            xddot = ( 6 * (1-param) * (self.x0_pt - 2*self.x1_pt + self.x2_pt) +
                      6 * param * (self.x1_pt - 2*self.x2_pt + self.x3_pt) )
            yddot = ( 6 * (1-param) * (self.y0_pt - 2*self.y1_pt + self.y2_pt) +
                      6 * param * (self.y1_pt - 2*self.y2_pt + self.y3_pt) )

            hypot = math.hypot(xdot, ydot)
            result.append((xdot*yddot - ydot*xddot) / hypot**3)
        return result 
Example #8
Source Project: twod_materials   Author: ashtonmv   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_markovian_path(points):
    """
    Calculates the shortest path connecting an array of 2D
    points.

    Args:
        points (list): list/array of points of the format
            [[x_1, y_1, z_1], [x_2, y_2, z_2], ...]

    Returns:
        A sorted list of the points in order on the markovian path.
    """

    def dist(x,y):
        return math.hypot(y[0] - x[0], y[1] - x[1])

    paths = [p for p in it.permutations(points)]
    path_distances = [
        sum(map(lambda x: dist(x[0], x[1]), zip(p[:-1], p[1:]))) for p in paths
    ]
    min_index = np.argmin(path_distances)

    return paths[min_index] 
Example #9
Source Project: convolutional-pose-machines-tensorflow   Author: timctho   File: cpm_utils.py    License: Apache License 2.0 6 votes vote down vote up
def warpImage(src, theta, phi, gamma, scale, fovy):
    halfFovy = fovy * 0.5
    d = math.hypot(src.shape[1], src.shape[0])
    sideLength = scale * d / math.cos(deg2Rad(halfFovy))
    sideLength = np.int32(sideLength)

    M = warpMatrix(src.shape[1], src.shape[0], theta, phi, gamma, scale, fovy)
    dst = cv2.warpPerspective(src, M, (sideLength, sideLength))
    mid_x = mid_y = dst.shape[0] // 2
    target_x = target_y = src.shape[0] // 2
    offset = (target_x % 2)

    if len(dst.shape) == 3:
        dst = dst[mid_y - target_y:mid_y + target_y + offset,
              mid_x - target_x:mid_x + target_x + offset,
              :]
    else:
        dst = dst[mid_y - target_y:mid_y + target_y + offset,
              mid_x - target_x:mid_x + target_x + offset]

    return dst 
Example #10
Source Project: pg   Author: fogleman   File: avoid.py    License: MIT License 6 votes vote down vote up
def update(self, bots):
        px, py = self.position
        tx, ty = self.target
        angle = atan2(ty - py, tx - px)
        dx = cos(angle)
        dy = sin(angle)
        for bot in bots:
            if bot == self:
                continue
            x, y = bot.position
            d = hypot(px - x, py - y) ** 2
            p = bot.padding ** 2
            angle = atan2(py - y, px - x)
            dx += cos(angle) / d * p
            dy += sin(angle) / d * p
        angle = atan2(dy, dx)
        magnitude = hypot(dx, dy)
        self.angle = angle
        return angle, magnitude 
Example #11
Source Project: VRPTW-ga   Author: shayan-ys   File: nodes.py    License: MIT License 5 votes vote down vote up
def get_distance_customers_pair(c1: Customer, c2: Customer) -> float:
    return math.hypot(c2.x - c1.x, c2.y - c1.y) 
Example #12
Source Project: pi-timolo   Author: pageauc   File: pi-timolo.py    License: MIT License 5 votes vote down vote up
def trackDistance(mPoint1, mPoint2):
    """
    Return the triangulated distance between two tracking locations
    """
    x1, y1 = mPoint1
    x2, y2 = mPoint2
    trackLen = abs(math.hypot(x2 - x1, y2 - y1))
    return trackLen

#------------------------------------------------------------------------------ 
Example #13
Source Project: pi-timolo   Author: pageauc   File: pi-timolo81.py    License: MIT License 5 votes vote down vote up
def trackDistance(mPoint1, mPoint2):
    x1, y1 = mPoint1
    x2, y2 = mPoint2
    trackLen = abs(math.hypot(x2 - x1, y2 - y1))
    return trackLen

#----------------------------------------------------------------------------------------------- 
Example #14
Source Project: dcs   Author: pydcs   File: mapping.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def distance(x1, y1, x2, y2):
    """Returns the distance between 2 points

    :param x1: x coordinate of point 1
    :param y1: y coordinate of point 1
    :param x2: x coordinate of point 2
    :param y2: y coordinate of point 2
    :return: distance in point units(m)
    """
    return math.hypot(x2 - x1, y2 - y1) 
Example #15
Source Project: renpy-shader   Author: bitsawer   File: delaunay.py    License: MIT License 5 votes vote down vote up
def distance(self, other):
        """Cartesian distance to other point """
        # only used in triangle.__str__
        return hypot(self.x -other.x, self.y - other.y) 
Example #16
Source Project: renpy-shader   Author: bitsawer   File: geometry.py    License: MIT License 5 votes vote down vote up
def pointDistance(p1, p2):
    return math.hypot(p2[0] - p1[0], p2[1] - p1[1]) 
Example #17
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testHypot(self):
        self.assertRaises(TypeError, math.hypot)
        self.ftest('hypot(0,0)', math.hypot(0,0), 0)
        self.ftest('hypot(3,4)', math.hypot(3,4), 5)
        self.assertEqual(math.hypot(NAN, INF), INF)
        self.assertEqual(math.hypot(INF, NAN), INF)
        self.assertEqual(math.hypot(NAN, NINF), INF)
        self.assertEqual(math.hypot(NINF, NAN), INF)
        self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
        self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) 
Example #18
Source Project: OctoPrint-ExcludeRegionPlugin   Author: bradcfisher   File: CircularRegion.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def containsPoint(self, x, y):
        """
        Check if the specified point is contained in this region.

        Returns
        -------
        True if the point is inside this region, and False otherwise.
        """
        return self.r >= math.hypot(x - self.cx, y - self.cy) 
Example #19
Source Project: python-in-practice   Author: lovexiaov   File: Board.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _nearest_to_middle(self, x, y, empty_neighbours):
        color = self.tiles[x][y]
        midX = self.columns // 2
        midY = self.rows // 2
        Δold = math.hypot(midX - x, midY - y)
        heap = []
        for nx, ny in empty_neighbours:
            if self._is_square(nx, ny):
                Δnew = math.hypot(midX - nx, midY - ny)
                if self._is_legal(nx, ny, color):
                    Δnew -= 0.1 # Make same colors slightly attractive
                heapq.heappush(heap, (Δnew, nx, ny))
        Δnew, nx, ny = heap[0]
        return (True, nx, ny) if Δold > Δnew else (False, x, y) 
Example #20
Source Project: python-in-practice   Author: lovexiaov   File: Board.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _nearest_to_middle(self, x, y, empty_neighbours):
        color = self.tiles[x][y]
        midX = self.columns // 2
        midY = self.rows // 2
        Δold = math.hypot(midX - x, midY - y)
        heap = []
        for nx, ny in empty_neighbours:
            if self._is_square(nx, ny):
                Δnew = math.hypot(midX - nx, midY - ny)
                if self._is_legal(nx, ny, color):
                    Δnew -= 0.1 # Make same colors slightly attractive
                heapq.heappush(heap, (Δnew, nx, ny))
        Δnew, nx, ny = heap[0]
        return (True, nx, ny) if Δold > Δnew else (False, x, y) 
Example #21
Source Project: Robofont-scripts   Author: loicsander   File: errorGlyph.py    License: MIT License 5 votes vote down vote up
def _setSize(self, size):
        self.si = size
        self.st = (
            250 - (size / 4),
            (750 / 2) - (size / 2)
            )
        self.le = hypot(size, size) / 4 
Example #22
Source Project: Robofont-scripts   Author: loicsander   File: errorGlyph.py    License: MIT License 5 votes vote down vote up
def _setSize(self, size):
        self.si = size
        self.st = (
            250 - (size / 4),
            (750 / 2) - (size / 2)
            )
        self.le = hypot(size, size) / 4 
Example #23
Source Project: Robofont-scripts   Author: loicsander   File: roundingTool.py    License: MIT License 5 votes vote down vote up
def mouseDragged(self, mousePoint, delta):
        if self.snatchedPoint is not None:
            snatchedPoint = self.snatchedPoint
            cut = False
            self._roundedGlyph = IntelGlyph(self._sourceGlyph)
            i1, i2 = self.getRoundedPointIndices(snatchedPoint)
            dx = snatchedPoint[0]-mousePoint[0]
            dy = snatchedPoint[1]-mousePoint[1]
            d = hypot(dx, dy)
            if self.shiftDown:
                d = round(d/5)*5
            d = int(d)
            limit = self.getLimit(snatchedPoint)
            if d > limit:
                d = limit
            if self.shiftDown and self.commandDown:
                d = 0
            if self.optionDown:
                cut = True
            self._roundedGlyph[i1][i2].labels['cornerRadius'] = d
            self._roundedGlyph[i1][i2].labels['cut'] = cut
            self._roundedGlyph.drawCornersByLabels()
            snatchedPoint.labels['cornerRadius'] = d
            snatchedPoint.labels['cut'] = cut
            self.snatchedPoint = snatchedPoint

    # def rightMouseDown(self, point, event):
    #     print "rightMouseDown"

    # def rightMouseDragged(self, point, delta):
    #     print "rightMouseDragged" 
Example #24
Source Project: Robofont-scripts   Author: loicsander   File: glyphObjects.py    License: MIT License 5 votes vote down vote up
def curveLength((a1, h1, h2, a2)):
    l = 0
    ax, ay = a1
    bx, by = h1
    cx, cy = h2
    dx, dy = a2
    for i in range(101):
        t = i/101
        x, y = pointOnACurve((ax, ay), (bx, by), (cx, cy), (dx, dy), t)
        if i > 0:
            l += hypot(x-px, y-py)
        px, py = x, y
    return l 
Example #25
Source Project: xy   Author: fogleman   File: field.py    License: MIT License 5 votes vote down vote up
def test(self, x, y):
        dx = 0
        dy = 0
        for px, py, pm in self.particles:
            d = hypot(x - px, y - py)
            if abs(d) < 1e-8:
                return (0, 0)
            angle = atan2(y - py, x - px)
            dx += pm * cos(angle) / d
            dy += pm * sin(angle) / d
        angle = atan2(dy, dx) #+ pi / 2
        dx = cos(angle)
        dy = sin(angle)
        return (dx, dy) 
Example #26
Source Project: xy   Author: fogleman   File: util.py    License: MIT License 5 votes vote down vote up
def join_paths(paths, tolerance=0.05):
    if len(paths) < 2:
        return paths
    result = [list(paths[0])]
    for path in paths[1:]:
        x1, y1 = result[-1][-1]
        x2, y2 = path[0]
        d = math.hypot(x2 - x1, y2 - y1)
        if d <= tolerance:
            result[-1].extend(path)
        else:
            result.append(list(path))
    return result 
Example #27
Source Project: xy   Author: fogleman   File: hashindex.py    License: MIT License 5 votes vote down vote up
def search(self, point):
        x, y = point[:2]
        i, j = self.normalize(x, y)
        points = []
        r = 0
        while not points:
            points.extend(self.load_ring(i, j, r))
            r += 1
        points.extend(self.load_ring(i, j, r))
        return min(points, key=lambda pt: (hypot(x - pt[0], y - pt[1]), pt[0], pt[1])) 
Example #28
Source Project: xy   Author: fogleman   File: turtles.py    License: MIT License 5 votes vote down vote up
def distance(self, x, y=None):
        if y is None:
            x, y = x
        return math.hypot(x - self.x, y - self.y) 
Example #29
Source Project: gaige   Author: markriedl   File: utils.py    License: MIT License 5 votes vote down vote up
def angle(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)) 
Example #30
Source Project: gaige   Author: markriedl   File: utils.py    License: MIT License 5 votes vote down vote up
def angle(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))