# Python math.isclose() Examples

The following are code examples for showing how to use math.isclose(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
 Project: zellij   Author: nedbat   File: test_euclid.py    (Apache License 2.0) View Source Project 8 votes
```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 ```
Example 2
 Project: zellij   Author: nedbat   File: test_path.py    (Apache License 2.0) View Source Project 6 votes
```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) ```
Example 3
 Project: pygorithm   Author: OmkarPathak   File: test_geometry.py    (license) View Source Project 6 votes
```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) ```
Example 4
 Project: pygorithm   Author: OmkarPathak   File: test_geometry.py    (license) View Source Project 6 votes
```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) ```
Example 5
 Project: pygorithm   Author: OmkarPathak   File: line2.py    (license) View Source Project 6 votes
```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) ```
Example 6
 Project: pygorithm   Author: OmkarPathak   File: axisall.py    (license) View Source Project 6 votes
```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 ```
Example 7
 Project: valhalla   Author: LCOGT   File: state_changes.py    (license) View Source Project 6 votes
```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 ```
Example 8
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 6 votes
```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)) ```
Example 9
 Project: online-judge-tools   Author: kmyk   File: test.py    (license) View Source Project 6 votes
```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 ```
Example 10
 Project: EWB-Drones-Navigation   Author: Rip-Lyster   File: navigationAlgoCode.py    (license) View Source Project 6 votes
```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 ```
Example 11
 Project: pysteamworks   Author: thedropbears   File: test_vision.py    (license) View Source Project 6 votes
```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) ```
Example 12
 Project: geo-py   Author: gojuno   File: test.py    (license) View Source Project 6 votes
```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) ```
Example 13
 Project: geo-py   Author: gojuno   File: test.py    (license) View Source Project 6 votes
```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) ```
Example 14
 Project: Population-Model-Compare   Author: selotape   File: test_tau_bounds.py    (license) View Source Project 6 votes
```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) ```
Example 15
 Project: Population-Model-Compare   Author: selotape   File: test_tau_bounds.py    (license) View Source Project 6 votes
```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) ```
Example 16
 Project: Population-Model-Compare   Author: selotape   File: test_tau_bounds.py    (license) View Source Project 6 votes
```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) ```
Example 17
 Project: IntroPython2016a   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 6 votes
```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)) ```
Example 18
 Project: conceptnet5   Author: ymmah   File: test_vectors.py    (license) View Source Project 6 votes
```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) ```
Example 19
 Project: zellij   Author: nedbat   File: test_euclid.py    (Apache License 2.0) View Source Project 5 votes
```def test_point_distance(p1, p2, result):
assert math.isclose(Point(*p1).distance(Point(*p2)), result) ```
Example 20
 Project: zellij   Author: nedbat   File: test_euclid.py    (Apache License 2.0) View Source Project 5 votes
```def test_line_angle(p1, p2, angle):
l = Line(Point(*p1), Point(*p2))
assert math.isclose(l.angle(), angle) ```
Example 21
 Project: zellij   Author: nedbat   File: postulates.py    (Apache License 2.0) View Source Project 5 votes
```def isclose(a, b):
"""Are two floats close together, even near zero."""
return math.isclose(a, b, abs_tol=1e-8) ```
Example 22
 Project: KerbalPie   Author: Vivero   File: kp_tools.py    (MIT License) View Source Project 5 votes
```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
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#- ```
Example 23
 Project: otRebuilder   Author: Pal3love   File: py23.py    (MIT License) View Source Project 5 votes
```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 ```
Example 24
 Project: caves   Author: mikaelho   File: vector.py    (license) View Source Project 5 votes
```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) ```
Example 25
 Project: pygorithm   Author: OmkarPathak   File: rect2.py    (license) View Source Project 5 votes
```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 ```
Example 26
 Project: pygorithm   Author: OmkarPathak   File: polygon2.py    (license) View Source Project 5 votes
```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 ```
Example 27
 Project: pygorithm   Author: OmkarPathak   File: rand_moving_stationary_generator.py    (license) View Source Project 5 votes
```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) ```
Example 28
 Project: monty   Author: boppreh   File: monty.py    (license) View Source Project 5 votes
```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) ```
Example 29
 Project: quran-typesetter   Author: khaledhosny   File: quran-typesetter.py    (license) View Source Project 5 votes
```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) ```
Example 30
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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)) ```
Example 31
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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 ```
Example 32
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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) ```
Example 33
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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. ```
Example 34
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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! ```
Example 35
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: test_trapz.py    (license) View Source Project 5 votes
```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) ```
Example 36
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: trapz_adapt.py    (license) View Source Project 5 votes
```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)) ```
Example 37
 Project: IntroPython2016   Author: UWPCE-PythonCert   File: trapz_adapt.py    (license) View Source Project 5 votes
```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") ```
Example 38
 Project: densecap-tensorflow   Author: rampage644   File: test_model.py    (license) View Source Project 5 votes
```def equal(a, b):
return math.isclose(a, b, abs_tol=0.001) ```
Example 39
 Project: valleyjudge   Author: dcolascione   File: valleyjudge.py    (license) View Source Project 5 votes
```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)) ```
Example 40
 Project: hexmachina   Author: dnkrtz   File: surfacemesh.py    (license) View Source Project 5 votes
```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 ```
Example 41
 Project: Udacity_Robotics_cs373   Author: lijiyao111   File: utils.py    (license) View Source Project 5 votes
```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 ```
Example 42
 Project: Udacity_AIND_Planning   Author: TilakD   File: utils.py    (license) View Source Project 5 votes
```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 ```
Example 43
 Project: axibot   Author: storborg   File: svg.py    (license) View Source Project 5 votes
```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 ```
Example 44
 Project: slicing_algorithm   Author: Nehri   File: slicing.py    (license) View Source Project 5 votes
```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 ```
Example 45
 Project: egtsimplex   Author: marvinboe   File: egtsimplex.py    (license) View Source Project 5 votes
```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([]) ```
Example 46
 Project: EWB-Drones-Navigation   Author: Rip-Lyster   File: navigationAlgoCode.py    (license) View Source Project 5 votes
```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 ```
Example 47
 Project: AIND-Planning   Author: udacity   File: utils.py    (license) View Source Project 5 votes
```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 ```
Example 48
 Project: KSURCT-TEST   Author: jisaiahgarrett   File: xbox.py    (license) View Source Project 5 votes
```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 ```
Example 49
 Project: gnosis-contracts   Author: gnosis   File: math_utils.py    (license) View Source Project 5 votes
```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) ```
Example 50
 Project: geo-py   Author: gojuno   File: test.py    (license) View Source Project 5 votes
```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 ```