Python math 模块,isclose() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.isclose()

项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def test_perpendicular(p1, p2, p3):
    assume(p1 != p2)
    l = Line(p1, p2)
    foot = l.foot(p3)
    perp = l.perpendicular(p3)
    print(foot)
    print(perp)

    # Property: foot should be on l.
    assert line_collinear(p1, p2, foot)

    # Property: foot should be on perp.
    assert line_collinear(perp.p1, perp.p2, foot)

    # Property: perp's angle should be 90 degrees from l's.
    angle_between = l.angle() - perp.angle()
    assert math.isclose(angle_between % 180, 90)


# Segments
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def test_combine_paths(paths):
    combined = combine_paths(paths)

    # Property: the points in the combined paths should all have been in the
    # original paths.
    assert point_set(paths) >= point_set(combined)

    # Property: the combined paths should have no duplicate endpoints.
    the_ends = endpoints(combined)
    assert len(the_ends) == len(set(the_ends))

    # Property: the combined paths should have the same or fewer segments as
    # the original paths.
    assert num_segments(paths) >= num_segments(combined)

    # Property: the combined paths should have the same total length as the
    # original paths.
    assert math.isclose(paths_length(paths), paths_length(combined))

    # Property: there should be no collinear triples in any path.
    assert not any(path.any_collinear() for path in combined)
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def test_from_regular_center(self):
        for i in range(3, 13):
            _poly = polygon2.Polygon2.from_regular(i, 1)

            foundx0 = False
            foundy0 = False
            for p in _poly.points:
                if math.isclose(p.x, 0, abs_tol=1e-07):
                    foundx0 = True
                    if foundy0:
                        break
                if math.isclose(p.y, 0, abs_tol=1e-07):
                    foundy0 = True
                    if foundx0:
                        break
            helpmsg = "\ni={}\nfoundx0={}, foundy0={}, center={}\nrepr={}\n\nstr={}".format(i, foundx0, foundy0, _poly.center, repr(_poly), str(_poly))
            self.assertTrue(foundx0, msg=helpmsg)
            self.assertTrue(foundy0, msg=helpmsg)
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def test_contains_point_regressions(self):
        # the fuzzer actually caught an error. put them in here to ensure they don't 
        # come back. The first issue was math.isclose without abs_tol on values close 
        # to 0 is too strict
        poly = polygon2.Polygon2([ (2, 3), (3, 5), (5, 4), (3, 2) ])

        regression_tests = [ (poly.points, vector2.Vector2(4, 3), True, False, vector2.Vector2(-509.47088031477625, 57.99699262312129)) ]
        for regression in regression_tests:
            points = regression[0]
            point = regression[1]
            expected_edge = regression[2]
            expected_contains = regression[3]
            offset = regression[4]

            new_points = []
            for pt in points:
                new_points.append(pt - offset)

            new_poly = polygon2.Polygon2(new_points)

            edge, cont = polygon2.Polygon2.contains_point(new_poly, offset, point)

            help_msg = "regression failed.\n\npoints={}, point={}, offset={}, expected_edge={}, expected_contains={}, edge={}, contains={}".format(points, point, offset, expected_edge, expected_contains, edge, cont)
            self.assertEqual(expected_edge, edge, msg=help_msg)
            self.assertEqual(expected_contains, cont, msg=help_msg)
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def are_parallel(line1, line2):
        """
        Determine if the two lines are parallel.

        Two lines are parallel if they have the same or opposite slopes.

        :param line1: the first line 
        :type line1: :class:`pygorithm.geometry.line2.Line2`
        :param line2: the second line
        :type line2: :class:`pygorithm.geometry.line2.Line2`
        :returns: if the lines are parallel
        :rtype: bool
        """

        if line1.vertical and line2.vertical:
            return True

        return math.isclose(line1.slope, line2.slope)
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def contains_point(line, point):
        """
        Determine if the line contains the specified point.

        The point must be defined the same way as min and max.

        .. tip::

            It is not possible for both returned booleans to be `True`.

        :param line: the line
        :type line: :class:`pygorithm.geometry.axisall.AxisAlignedLine`
        :param point: the point
        :type point: :class:`numbers.Number`
        :returns: (if the point is an edge of the line, if the point is contained by the line)
        :rtype: (bool, bool)
        """

        if math.isclose(line.min, point) or math.isclose(line.max, point):
            return True, False
        elif point < line.min or point > line.max:
            return False, False
        else:
            return False, True
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def get_request_state_from_pond_blocks(request_state, acceptability_threshold, request_blocks):
    active_blocks = False
    future_blocks = False
    now = timezone.now()
    for block in request_blocks:
        start_time = dateutil.parser.parse(block['start']).replace(tzinfo=timezone.utc)
        end_time = dateutil.parser.parse(block['end']).replace(tzinfo=timezone.utc)
        # mark a block as complete if a % of the total exposures of all its molecules are complete
        completion_percent = exposure_completion_percentage_from_pond_block(block)
        if isclose(acceptability_threshold, completion_percent) or completion_percent >= acceptability_threshold:
            return 'COMPLETED'
        if (not block['canceled'] and not any(molecule['failed'] for molecule in block['molecules'])
                and start_time < now < end_time):
            active_blocks = True
        if now < start_time:
            future_blocks = True

    if not (future_blocks or active_blocks):
        return 'FAILED'

    return request_state
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_sloping_line():
    ''' a simple linear function '''
    def line(x):
        return 2 + 3*x

    # I got 159.99999999999 rather than 160
    #   hence the need for isclose()
    assert isclose(trapz(line, 2, 10), 160)
    m, B = 3, 2
    a, b = 0, 5
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))

    a, b = 5, 10
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))

    a, b = -10, 5
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
项目:online-judge-tools    作者:kmyk    | 项目源码 | 文件源码
def compare_as_floats(xs, ys, error):
    def f(x):
        try:
            y = float(x)
            if not math.isfinite(y):
                log.warning('not an real number found: %f', y)
            return y
        except ValueError:
            return x
    xs = list(map(f, xs.split()))
    ys = list(map(f, ys.split()))
    if len(xs) != len(ys):
        return False
    for x, y in zip(xs, ys):
        if isinstance(x, float) and isinstance(y, float):
            if not math.isclose(x, y, rel_tol=error, abs_tol=error):
                return False
        else:
            if x != y:
                return False
    return True
项目:EWB-Drones-Navigation    作者:Rip-Lyster    | 项目源码 | 文件源码
def getPointsBtwnVertices(v1, v2, dx):
    """
        accepts:
            v1: the position of one vertex
            v2: the position of the other vertex
            dx: stride length
        returns:
            points: ordered list of points between v1 and v2 at which to take a photo

    """
    points = []
    v1x, v2x = v1[0], v2[0]
    v1y, v2y = v1[1], v2[1]
    if np.isclose(v1x, v2x):
        return getPointsonVerticalLine(v1x, v1y, v2y, dx)
    if v2x-v1x<0: dx = -dx
    xPoints = int((v2x - v1x) / dx)
    dy = (v2y - v1y) / (v2x - v1x) * dx
    x, y = v1x, v1y
    for pointNo in range(xPoints):
        points.append((x, y))
        x += dx
        y += dy
    return points
项目:pysteamworks    作者:thedropbears    | 项目源码 | 文件源码
def test_sample_images():
    variables = ['x', 'nt']
    with open('sample_img/tests.csv', 'r') as csvfile:
        # filename, x, y, w, h
        testreader = csv.reader(csvfile, delimiter=',')
        for sample in testreader:
            image = cv2.imread('sample_img/' + sample[0])
            # Rescale if necessary
            height, width, channels = image.shape
            x, img, num_targets, target_sep = find_target(image)
            assert num_targets == int(sample[2])
            if num_targets == 0:
                x = None
                continue
            if x != None and sample[1] != None:
                sample[1] = 2 * float(sample[1]) / width - 1
                assert math.isclose(x, sample[1], abs_tol=0.1)
项目:geo-py    作者:gojuno    | 项目源码 | 文件源码
def test_projection(self):
        x, y = sphere._py_from4326_to3857(p_minsk)
        assert math.isclose(x, 3068168.9922502628, rel_tol=1e-06)
        assert math.isclose(y, 7151666.629430503, rel_tol=1e-06)
        x, y = _sphere._from4326_to3857(p_minsk)
        assert math.isclose(x, 3068168.9922502628, rel_tol=1e-06)
        assert math.isclose(y, 7151666.629430503, rel_tol=1e-06)

        lon, lat = sphere._py_from3857_to4326(
            sphere._py_from4326_to3857(p_minsk))
        assert math.isclose(lon, p_minsk[0], rel_tol=1e-06)
        assert math.isclose(lat, p_minsk[1], rel_tol=1e-06)

        lon, lat = _sphere._from3857_to4326(
            _sphere._from4326_to3857(p_minsk))
        assert math.isclose(lon, p_minsk[0], rel_tol=1e-06)
        assert math.isclose(lat, p_minsk[1], rel_tol=1e-06)
项目:geo-py    作者:gojuno    | 项目源码 | 文件源码
def test_projection(self):
        assert (
            ellipsoid._py_from4326_to3395(p_minsk) ==
            (3068168.9922502623, 7117115.955611216)
        )
        rp_minsk = ellipsoid._py_from3395_to4326(
                ellipsoid._py_from4326_to3395(p_minsk))

        assert math.isclose(rp_minsk[0], p_minsk[0], rel_tol=1e-06)
        assert math.isclose(rp_minsk[1], p_minsk[1], rel_tol=1e-06)

        assert (
            _ellipsoid._from4326_to3395(p_minsk) ==
            (3068168.9922502623, 7117115.955611216)
        )

        rp_minsk = _ellipsoid._from3395_to4326(
                _ellipsoid._from4326_to3395(p_minsk))

        assert math.isclose(rp_minsk[0], p_minsk[0], rel_tol=1e-06)
        assert math.isclose(rp_minsk[1], p_minsk[1], rel_tol=1e-06)
项目:Population-Model-Compare    作者:selotape    | 项目源码 | 文件源码
def test_large_pop_tree():
    ROOT = Population(name='ROOT')

    AB = Population(name='AB', father=ROOT)
    A = Population(name='A', father=AB)
    B = Population(name='B', father=AB)

    CD = Population(name='CD', father=ROOT)
    C = Population(name='C', father=CD)
    D = Population(name='D', father=CD)

    a = Event(time=0.0, lca_pop=A)
    b = Event(time=0.0, lca_pop=B)
    ab = Event(time=0.5, left=a, right=b)

    c = Event(time=0.0, lca_pop=C)
    d = Event(time=0.0, lca_pop=D)
    cd = Event(time=0.6, left=c, right=d)

    r = Event(time=1.0, left=ab, right=cd)

    tau_bounds = find_tau_bounds(r)

    for pop, event in ((A, a), (B, b), (C, c), (D, d), (AB, ab), (CD, cd), (ROOT, r)):
        assert isclose(tau_bounds[pop], event.time)
项目:Population-Model-Compare    作者:selotape    | 项目源码 | 文件源码
def test_multiple_bounders():
    AB = Population(name='AB')
    A = Population(name='A', father=AB)
    B = Population(name='B', father=AB)

    a = Event(time=0.0, lca_pop=A)
    b = Event(time=0.0, lca_pop=B)
    c = Event(time=0.0, lca_pop=B)
    d = Event(time=0.0, lca_pop=B)
    ab = Event(time=0.5, left=a, right=b)
    abc = Event(time=0.6, left=ab, right=c)
    abcd = Event(time=0.7, left=abc, right=d)

    tau_bounds = find_tau_bounds(abcd)

    assert isclose(tau_bounds[AB], ab.time)
项目:Population-Model-Compare    作者:selotape    | 项目源码 | 文件源码
def test_bounder_bounds_multiple_pops():
    ABC = Population(name='ABC')
    AB = Population(name='AB', father=ABC)
    C = Population(name='C', father=ABC)
    A = Population(name='A', father=AB)
    B = Population(name='B', father=AB)
    AB.left, AB.right = A, B
    ABC.left, ABC.right = AB, C

    a = Event(time=0.0, lca_pop=A)
    c = Event(time=0.0, lca_pop=C)
    ac = Event(time=0.5, left=a, right=c)

    tau_bounds = find_tau_bounds(ac)

    assert isclose(tau_bounds[AB], ac.time)
    assert isclose(tau_bounds[ABC], ac.time)
项目:IntroPython2016a    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_sloping_line():
    ''' a simple linear function '''
    def line(x):
        return 2 + 3*x

    # I got 159.99999999999 rather than 160
    #   hence the need for isclose()
    assert isclose(trapz(line, 2, 10), 160)
    m, B = 3, 2
    a, b = 0, 5
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))

    a, b = 5, 10
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))

    a, b = -10, 5
    assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
项目:conceptnet5    作者:ymmah    | 项目源码 | 文件源码
def test_shrink_and_sort(frame=None):
    if not frame:
        frame = DATA + '/vectors/glove12-840B.h5'
    vectors = load_any_embeddings(frame)

    n, k = 10, 20
    shrank = shrink_and_sort(vectors, n, k)

    # Check the size of the frame
    ok_(shrank.shape == (n, k))

    # Check if the frame is l2 normalized
    lengths = np.sqrt(np.sum(np.power(shrank, 2), axis='columns'))
    ok_(all(isclose(length, 1.0, rel_tol=1e-04) for length in lengths))

    # Check if the index is sorted
    ok_(shrank.index.is_monotonic_increasing)
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def test_point_distance(p1, p2, result):
    assert math.isclose(Point(*p1).distance(Point(*p2)), result)
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def test_line_angle(p1, p2, angle):
    l = Line(Point(*p1), Point(*p2))
    assert math.isclose(l.angle(), angle)
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def isclose(a, b):
    """Are two floats close together, even near zero."""
    return math.isclose(a, b, abs_tol=1e-8)
项目:KerbalPie    作者:Vivero    | 项目源码 | 文件源码
def has_changed(self, to_value=None):
        if len(self._shift_register) > 1:
            if to_value is not None:
                # if we are comparing to a given value (that matches the data class)...
                if to_value.__class__ != self._data_class:
                    return None

                if self._data_class == float:
                    # compare with isclose, for floats
                    return math.isclose(self._shift_register[-1], to_value, rel_tol=1.0e-6) and self.has_changed()
                else:
                    # compare with equality, otherwise
                    return (self._shift_register[-1] == to_value) and self.has_changed()

            else:
                # if we are just checking if the latest value changed at all
                if self._data_class == float:
                    # compare with isclose, for floats
                    return not math.isclose(self._shift_register[-1], self._shift_register[-2])
                else:
                    # compare with equality, otherwise
                    return (self._shift_register[-1] != self._shift_register[-2])

        else:
            return False





#--- Basic PID controller class
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
项目:otRebuilder    作者:Pal3love    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0):
        """
        Python 2 implementation of Python 3.5 math.isclose()
        https://hg.python.org/cpython/file/v3.5.2/Modules/mathmodule.c#l1993
        """
        # sanity check on the inputs
        if rel_tol < 0 or abs_tol < 0:
            raise ValueError("tolerances must be non-negative")
        # short circuit exact equality -- needed to catch two infinities of
        # the same sign. And perhaps speeds things up a bit sometimes.
        if a == b:
            return True
        # This catches the case of two infinities of opposite sign, or
        # one infinity and one finite number. Two infinities of opposite
        # sign would otherwise have an infinite relative tolerance.
        # Two infinities of the same sign are caught by the equality check
        # above.
        if _isinf(a) or _isinf(b):
            return False
        # Cast to float to allow decimal.Decimal arguments
        if not isinstance(a, float):
            a = float(a)
        if not isinstance(b, float):
            b = float(b)
        # now do the regular computation
        # this is essentially the "weak" test from the Boost library
        diff = _fabs(b - a)
        result = ((diff <= _fabs(rel_tol * a)) or
                  (diff <= _fabs(rel_tol * b)) or
                  (diff <= abs_tol))
        return result
项目:caves    作者:mikaelho    | 项目源码 | 文件源码
def __eq__(self, other):
    return math.isclose(self[0], other[0], abs_tol=self.abs_tol) and math.isclose(self[1], other[1], abs_tol=self.abs_tol)
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def contains_point(rect, point):
        """
        Determine if the rect contains the point

        Distinguish between points that are on the edge of the
        rect and those that are not.

        .. tip::

            This will never return ``True, True``

        :param rect: the rect
        :type rect: :class:`pygorithm.geometry.rect2.Rect2`
        :param point: the point
        :type point: :class:`pygorithm.geometry.vector2.Vector2`
        :returns: point on edge, point inside
        :rtype: bool, bool
        """

        edge_x = math.isclose(rect.mincorner.x, point.x, abs_tol=1e-07) or math.isclose(rect.mincorner.x + rect.width, point.x, abs_tol=1e-07)
        edge_y = math.isclose(rect.mincorner.y, point.y, abs_tol=1e-07) or math.isclose(rect.mincorner.y + rect.height, point.y, abs_tol=1e-07)
        if edge_x and edge_y:
            return True, False

        contains = (edge_x or (point.x > rect.mincorner.x and point.x < rect.mincorner.x + rect.width)) and \
                   (edge_y or (point.y > rect.mincorner.y and point.y < rect.mincorner.y + rect.height))
        if not contains:
            return False, False
        elif edge_x or edge_y:
            return True, False
        else:
            return False, True
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def contains_point(polygon, offset, point):
        """
        Determine if the polygon at offset contains point.

        Distinguish between points that are on the edge of the polygon and 
        points that are completely contained by the polygon.

        .. tip::

            This can never return True, True

        This finds the cross product of this point and the two points comprising
        every line on this polygon. If any are 0, this is an edge. Otherwise,
        they must all be negative (when traversed clockwise).

        :param polygon: the polygon 
        :type polygon: :class:`pygorithm.geometry.polygon2.Polygon2`
        :param offset: the offset of the polygon
        :type offset: :class:`pygorithm.geometry.vector2.Vector2` or None
        :param point: the point to check
        :type point: :class:`pygorithm.geometry.vector2.Vector2`
        :returns: on edge, contained
        :rtype: bool, bool
        """

        _previous = polygon.points[0]
        for i in range(1, len(polygon.points) + 1):
            curr = polygon.points[i % len(polygon.points)]

            vec1 = _previous + offset - point
            vec2 = curr + offset - point
            cross = vec1.cross(vec2)
            _previous = curr

            if math.isclose(cross, 0, abs_tol=1e-07):
                return True, False

            if cross > 0:
                return False, False

        return False, True
项目:pygorithm    作者:OmkarPathak    | 项目源码 | 文件源码
def test_collinear(pt1, pt2, pt3):
    Ax = pt1[0]
    Ay = pt1[1]
    Bx = pt2[0]
    By = pt2[1]
    Cx = pt3[0]
    Cy = pt3[1]
    return math.isclose(Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By), 0, abs_tol=1e-07)
项目:monty    作者:boppreh    | 项目源码 | 文件源码
def normalize(self):
        """
        Returns a new distribution with the probabilities normalized so that
        their total sums to 1.
        """
        if math.isclose(self.total, 1) or self.total == 0:
            return self
        return Distribution(*((v, p/self.total) for v, p in self), force_flatten=self.force_flatten, force_merge=self.force_merge)
项目:quran-typesetter    作者:khaledhosny    | 项目源码 | 文件源码
def draw(self, cr, pos, text_width):
        self.strip()
        width = sum([box.width for box in self.boxes])
        # Center lines not equal to text width.
        if not math.isclose(width, text_width):
            pos.x -= (text_width - width)/2

        for box in self.boxes:
            # We start drawing from the right edge of the text block,
            # and move to the left, thus the subtraction instead of
            # addition below.
            pos.x -= box.width
            box.draw(cr, pos)
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        """
        Determine whether two floating point numbers are close in value.

        rel_tol
           maximum difference for being considered "close", relative to the
           magnitude of the input values
        abs_tol
           maximum difference for being considered "close", regardless of the
           magnitude of the input values

        Return True if a is close in value to b, and False otherwise.

        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.

        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
        """

        if rel_tol < 0.0 or abs_tol < 0.0:
            raise ValueError('error tolerances must be non-negative')

        if a == b:  # short-circuit exact equality
            return True
        if math.isinf(a) or math.isinf(b):
            # This includes the case of two infinities of opposite sign, or
            # one infinity and one finite number. Two infinities of opposite sign
            # would otherwise have an infinite relative tolerance.
            return False
        diff = abs(b - a)
        return (((diff <= abs(rel_tol * b)) and
                 (diff <= abs(rel_tol * a))) or
                (diff <= abs_tol))
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_is_close():
    ''' just to make sure '''
    assert isclose(4.5, 4.5)
    assert isclose(4.5, 4.499999999999999999)

    assert not isclose(4.5, 4.6)
    # of course, not comprehesive!


# you need to compute a bunch of evenly spaced numbers from a to b
#  kind of like range() but for floating point numbers
# I did it as a separate function so I could test it
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_sine():
    #  a sine curve from zero to pi -- should be 2
    # with a hundred points, only correct to about 4 figures
    assert isclose(trapz(math.sin, 0, math.pi), 2.0, rel_tol=1e-04)
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_sine2():
    #  a sine curve from zero to 2pi -- should be 0.0
    # need to set an absolute tolerance when comparing to zero
    assert isclose(trapz(math.sin, 0, 2*math.pi), 0.0, abs_tol=1e-8)


# test the quadratic function itself
#   this is pytest's way to test a bunch of input and output values
#   it creates a separate test for each case.
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_quadratic_trapz_args_kwargs():
    """
    Testing if you can pass a combination of positional and keyword arguments
    one case: A=2, B=-4, C=3
    """
    A, B, C = 2, -4, 3
    a, b = -2, 2
    assert isclose(trapz(quadratic, a, b, A, B, C=C),
                   quad_solution(a, b, A, B, C),
                   rel_tol=1e-3)  # not a great tolerance -- maybe should try more samples!
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def test_sine_freq_amp():
    a = 0
    b = 5
    omega = 0.5
    amp = 10
    assert isclose(trapz(sine_freq_amp, a, b, amp=amp, freq=omega),
                   solution_freq_amp(a, b, amp, omega),
                   rel_tol=1e-04)
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        """
        Determine whether two floating point numbers are close in value.

        rel_tol
           maximum difference for being considered "close", relative to the
           magnitude of the input values
        abs_tol
           maximum difference for being considered "close", regardless of the
           magnitude of the input values

        Return True if a is close in value to b, and False otherwise.

        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.

        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
        """

        if rel_tol < 0.0 or abs_tol < 0.0:
            raise ValueError('error tolerances must be non-negative')

        if a == b:  # short-circuit exact equality
            return True
        if math.isinf(a) or math.isinf(b):
            # This includes the case of two infinities of opposite sign, or
            # one infinity and one finite number. Two infinities of opposite sign
            # would otherwise have an infinite relative tolerance.
            return False
        diff = abs(b - a)
        return (((diff <= abs(rel_tol * b)) and
                 (diff <= abs(rel_tol * a))) or
                (diff <= abs_tol))
项目:IntroPython2016    作者:UWPCE-PythonCert    | 项目源码 | 文件源码
def trapz(fun, a, b, tol=1e-4, *args, **kwargs):
    """
    Compute the area under the curve defined by
    y = fun(x), for x between a and b

    :param fun: the function to evaluate
    :type fun: a function that takes teh vule to be integrated over as
               its first argument. Any arguments can be passed in at the end.

    :param a: the start point for the integration
    :type a: a numeric value

    :param b: the end point for the integration
    :type b: a numeric value

    :param tol=1e-4: accuracy expected.

    any other arguments will be passed through to fun.
    """
    # compute the range

    # loop to try varying step sizes until desired accuracey is achieved

    prev_s = None
    n = 2  # start with only two steps
    while True:  # break out when desired accuracy is reached
        vals = frange(a, b, n)
        s = sum([fun(x, *args, **kwargs) for x in vals[1:-1]])
        s += (fun(a, *args, **kwargs) + fun(b, *args, **kwargs)) / 2
        s *= (b-a) / n
        if prev_s is not None:
            # check if we're close enough
            # abs_tol is for comparison to zero
            if isclose(s, prev_s, rel_tol=tol, abs_tol=tol):
                return s
        n *= 2
        prev_s = s
        # this could be a more sophisticated criterion
        if n >= 2**22:  # it's not going to work (about half the precision of a double)
            raise ValueError("Solution didn't converge")
项目:densecap-tensorflow    作者:rampage644    | 项目源码 | 文件源码
def equal(a, b):
    return math.isclose(a, b, abs_tol=0.001)
项目:valleyjudge    作者:dcolascione    | 项目源码 | 文件源码
def __init__(self,
                 *,
                 total,
                 start = None,
                 vesting_dates = DEFAULT_VESTING_DATES,
                 vesting = (0.25, 0.25, 0.25, 0.25)):
        """Create an equity grant description.

        TOTAL is the total size, in dollars, of the grant.  START is
        the date on which it starts; if None, the grant clock starts
        on the company start date.  VESTING_DATES is a sequence of
        (MONTH, DAY) pairs on which equity grants vest --- a grant
        that vests quarterly will have a four-element
        VESTING_DATES sequence.

        VESTING is a sequence of numbers that sum to 1.0.  With default
        vesting dates, each one represents a year over which the grant vests, 
        and the value of the number indicates the portion of the grant that 
        vests in that year.

        """
        self.total = typecheck(total, numbers.Real)
        self.start = typecheck(start, (date, timedelta, type(None)))
        self.vesting_dates = typecheck(vesting_dates, seq_of(pair_of(int)))
        self.vesting = typecheck(vesting, seq_of(numbers.Real))
        if not math.isclose(sum(vesting), 1.0, rel_tol=1e-5):
            raise ValueError("vesting fractions do not sum to 1: %1.5f" % sum(vesting))
项目:hexmachina    作者:dnkrtz    | 项目源码 | 文件源码
def diagonalize_curvature(cls, old_u, old_v, ku, kuv, kv, new_norm):
        """Given a curvature tensor, diagonalize to find principal directions and curvatures."""
        # Rotate old coord system to be normal to new.
        r_old_u, r_old_v = cls.rotate_coord_sys(old_u, old_v, new_norm)
        c = 1
        s = 0
        tt = 0
        if not math.isclose(kuv, 0):
            # Jacobi rotation to diagonalize.
            h = 0.5 * (kv - ku) / kuv
            if h < 0:
                tt = 1 / (h - math.sqrt(1 + h*h))
            else:
                tt = 1 / (h + math.sqrt(1 + h*h))
            c = 1 / math.sqrt(1 + tt*tt)
            s = tt * c
        # Compute principal curvatures.
        k1 = ku - tt * kuv
        k2 = kv + tt * kuv

        # Compute principal directions.
        if abs(k1) >= abs(k2):
            pdir1 = c * r_old_u - s * r_old_v
        else:
            k1, k2 = k2, k1 # swap
            pdir1 = s * r_old_u + c * r_old_v
        pdir2 = np.cross(new_norm, pdir1)
        # Return all the things.
        return pdir1, pdir2, k1, k2
项目:Udacity_Robotics_cs373    作者:lijiyao111    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        "Return true if numbers a and b are close to each other."
        return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

# ______________________________________________________________________________
# Misc Functions


# TODO: Use functools.lru_cache memoization decorator
项目:Udacity_AIND_Planning    作者:TilakD    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        "Return true if numbers a and b are close to each other."
        return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

# ______________________________________________________________________________
# Misc Functions


# TODO: Use functools.lru_cache memoization decorator
项目:axibot    作者:storborg    | 项目源码 | 文件源码
def get_document_dimensions(tree, max_area=(11.0, 8.5)):
    """
    Return the dimensions of this document in inches as to be plotted. If the
    document specifies physical units, they will be converted to inches, and
    asserted to be less than the working area of the AxiDraw. If the document
    does not specify physical units (e.g. the width and height are in pixels
    only) it will be scaled to the working area.

    Returns a tuple of (width, height) in inches.
    """
    max_width, max_height = max_area
    raw_width = tree.get('width')
    raw_height = tree.get('height')
    if not (raw_width and raw_height):
        log.warn("This document does not have width and height attributes. "
                 "Extracting viewbox dimensions.")
        svg_width = svg_height = None
        raw_width, raw_height = get_viewbox_dimensions(tree.get('viewBox'))
    else:
        svg_width = convert_to_inches(raw_width)
        svg_height = convert_to_inches(raw_height)
    if not (svg_width and svg_height):
        log.warn("This document does not specify physical units. "
                 "Auto-scaling it to fit the drawing area.")
        width = parse_pixels(raw_width)
        height = parse_pixels(raw_height)
        aspect_ratio = width / height
        max_ratio = max_width / max_height
        if aspect_ratio > max_ratio:
            # Wider than working area, constrained by width
            scale = max_width / width
        else:
            # Taller than working area, constrained by height
            scale = max_height / height
        svg_width = scale * width
        svg_height = scale * height
    assert svg_width <= max_width or math.isclose(svg_width, max_width), \
        "SVG width of %s must be <= %s" % (svg_width, max_width)
    assert svg_height <= max_height or math.isclose(svg_height, max_height), \
        "SVG height of %s must be <= %s" % (svg_height, max_height)
    return svg_width, svg_height
项目:slicing_algorithm    作者:Nehri    | 项目源码 | 文件源码
def intersection(L1,L2):

    #make sure all lines are on the same z plane
    #assert (math.isclose(L1.p0.z, L1.p1.z, abs_tol=0.0001))
    #assert (L2.p0.z == L2.p1.z)
    #assert (L1.p0.z == L2.p0.z)

    x1 = L1.p0.x
    y1 = L1.p0.y
    x2 = L1.p1.x
    y2 = L1.p1.y
    x3 = L2.p0.x
    y3 = L2.p0.y
    x4 = L2.p1.x
    y4 = L2.p1.y

    xnum = (x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)
    xden = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
    ynum = (x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)
    yden = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)

    try:
        intersect = Point(xnum/xden,ynum/yden,L1.p0.z) 

        if ((intersect.x >= min(x1,x2)-delta) and (intersect.x <= max(x1,x2)+delta) and
            (intersect.y >= min(y1,y2)-delta) and (intersect.y <= max(y1,y2)+delta) and
            (intersect.x >= min(x3,x4)-delta) and (intersect.x <= max(x3,x4)+delta) and
            (intersect.y >= min(y3,y4)-delta) and (intersect.y <= max(y3,y4)+delta)):
            return intersect
        else:
            return None
        # return intersect
    except:
        return None

#given a list of lines that make a manifold perimeter on a slice,
#and a percentage of space that should be infill,
#returns a list of infill lines (grid pattern) for that slice
#assumes print bed area is a square
项目:egtsimplex    作者:marvinboe    | 项目源码 | 文件源码
def calculate_stationary_points(self):
        fp_raw=[]
        border=5 #don't check points close to simplex border
        delta=1e-12
        for x,y in zip(self.trimesh.x[border:-border], self.trimesh.y[border:-border]):
            start=self.xy2ba(x,y)
            fp_try=np.array([])

            sol=scipy.optimize.root(self.f,start,args=(0,),method="hybr")#,xtol=1.49012e-10,maxfev=1000
            if sol.success:
                fp_try=sol.x
                #check if FP is in simplex
                if not math.isclose(np.sum(fp_try), 1.,abs_tol=2.e-3):
                    continue
                if not np.all((fp_try>-delta) & (fp_try <1+delta)):#only if fp in simplex
                    continue
            else:
                continue
            #only add new fixed points to list
            if not np.array([np.allclose(fp_try,x,atol=1e-7) for x in fp_raw]).any():
                    fp_raw.append(fp_try.tolist())
        #add fixed points in correct coordinates to fixpoints list
        fp_raw=np.array(fp_raw)
        if fp_raw.shape[0]>0:
            self.fixpoints=self.corners.T.dot(np.array(fp_raw).T).T
        else:
            self.fixpoints=np.array([])
项目:EWB-Drones-Navigation    作者:Rip-Lyster    | 项目源码 | 文件源码
def getLineEnd(x, yStart, perimeterPoints):
    """accepts:
            (x,yStart): position of perimeter point
            perimeterPoints: list of perimeter points, used to check which one is immediately below (x,yStart)
         returns:
            yEnd: when combined into (x,yEnd), it is the coordinates of the point on the perimeter immediately below (x,yStart)
                NOTE: yEnd is None if there is no such point
    """
    pointsBelow = 0
    yEnd = None
    for index1 in range(len(perimeterPoints)):
        index2 = (index1 + 1)%len(perimeterPoints)
        if (x, yStart) == perimeterPoints[index1] \
        or (x, yStart) == perimeterPoints[index2]:
            continue
        x0, x1 = perimeterPoints[index1][0], perimeterPoints[index2][0]
        if min(x0, x1)<= x <= max(x0, x1) and x0 != x1:
            #print(x0, x1)
            y0, y1 = perimeterPoints[index1][1], perimeterPoints[index2][1]
            #if math.isclose(x0, x1):
            #    y = max(y0, y1)
                #print(y,"!")
            #else:
            y = (y1-y0)/(x1-x0) * (x-x0) + y0
            if y > yStart and (yEnd == None or y < yEnd):
                pointsBelow += 1
                yEnd = y
    if pointsBelow % 2 == 0: yEnd = None
    return yEnd
项目:AIND-Planning    作者:udacity    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        "Return true if numbers a and b are close to each other."
        return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

# ______________________________________________________________________________
# Misc Functions


# TODO: Use functools.lru_cache memoization decorator
项目:KSURCT-TEST    作者:jisaiahgarrett    | 项目源码 | 文件源码
def value(self):
        normal = self.__value - self.zero_value
        if self.__value > 0:
            normal = normal / (self.VAR_MAX - self.zero_value)
        else:
            normal = -normal / (self.VAR_MIN - self.zero_value)

        if isclose(normal, 0, abs_tol=0.04):
            return 0
        return normal
项目:gnosis-contracts    作者:gnosis    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
        return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
项目:geo-py    作者:gojuno    | 项目源码 | 文件源码
def isclose(a, b, rel_tol=1e-09, abs_tol=0):
    """
    Python 2 implementation of Python 3.5 math.isclose()
    https://hg.python.org/cpython/file/v3.5.2/Modules/mathmodule.c#l1993
    """
    # sanity check on the inputs
    if rel_tol < 0 or abs_tol < 0:
        raise ValueError("tolerances must be non-negative")
    # short circuit exact equality -- needed to catch two infinities of
    # the same sign. And perhaps speeds things up a bit sometimes.
    if a == b:
        return True
    # This catches the case of two infinities of opposite sign, or
    # one infinity and one finite number. Two infinities of opposite
    # sign would otherwise have an infinite relative tolerance.
    # Two infinities of the same sign are caught by the equality check
    # above.
    if math.isinf(a) or math.isinf(b):
        return False
    # Cast to float to allow decimal.Decimal arguments
    if not isinstance(a, float):
        a = float(a)
    if not isinstance(b, float):
        b = float(b)
    # now do the regular computation
    # this is essentially the "weak" test from the Boost library
    diff = math.fabs(b - a)
    result = ((diff <= math.fabs(rel_tol * a)) or
              (diff <= math.fabs(rel_tol * b)) or
              (diff <= abs_tol))
    return result