# Python math.isclose() Examples

The following are 30 code examples of math.isclose(). 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 , or try the search function .
Example #1
```def calc_price_change(ratio, min_price_move=DEF_MIN_PRICE_MOVE,
max_price_move=DEF_MAX_PRICE_MOVE):
"""
Make the price move in proportion to the ratio, up to a ceiling
of max_price_move.
"""
direction = 1
if isclose(ratio, 1.0):
return 0

if ratio < 1:
if ratio == 0:
ratio = INF
else:
ratio = 1 / ratio
direction = -1

return direction * min(max_price_move, min_price_move * ratio) ```
Example #2
```def pad_filter(probe):
"""
if source and target aspect is different,
fix it with pillarbox or letterbox
"""
filter_chain = []

if not math.isclose(probe.video[0]['aspect'],
_pre_comp.aspect, abs_tol=0.03):
if probe.video[0]['aspect'] < _pre_comp.aspect:
filter_chain.append(
_pre_comp.h))
elif probe.video[0]['aspect'] > _pre_comp.aspect:
filter_chain.append(
_pre_comp.w))

return filter_chain ```
Example #3
```def scale_filter(probe):
"""
if target resolution is different to source add scale filter,
apply also an aspect filter, when is different
"""
filter_chain = []

if int(probe.video[0]['width']) != _pre_comp.w or \
int(probe.video[0]['height']) != _pre_comp.h:
filter_chain.append('scale={}:{}'.format(_pre_comp.w, _pre_comp.h))

if not math.isclose(probe.video[0]['aspect'],
_pre_comp.aspect, abs_tol=0.03):
filter_chain.append('setdar=dar={}'.format(_pre_comp.aspect))

return filter_chain ```
Example #4
```def get_delta(begin):
"""
get difference between current time and begin from clip in playlist
"""
current_time = get_time('full_sec')

if _playlist.length:
target_playtime = _playlist.length
else:
target_playtime = 86400.0

if _playlist.start >= current_time and not begin == _playlist.start:
current_time += target_playtime

current_delta = begin - current_time

if math.isclose(current_delta, 86400.0, abs_tol=6):
current_delta -= 86400.0

ref_time = target_playtime + _playlist.start
total_delta = ref_time - begin + current_delta

return current_delta, total_delta ```
Example #5
```def test_ecm_init(self):

m = np.array([0.23, .81, .85, .81, .85, .81])
u = np.array([0.34, .23, .50, .23, .30, 0.13])

# Create the train dataset.
1000, 500, m=m, u=u, random_state=535, return_links=True)

ecm = rl.ECMClassifier(init='random')
ecm.fit(X_train)
ecm.predict(X_train)

print(ecm.m_probs)
print(ecm.log_m_probs)
print(ecm.u_probs)
print(ecm.log_u_probs)

assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08) ```
Example #6
```def test_ecm_init_random_1value(self):

m = np.array([1.0, .81, .85, .81, .85, .81])
u = np.array([1.0, .23, .50, .23, .30, 0.13])

# Create the train dataset.
1000, 500, m=m, u=u, random_state=536, return_links=True)

ecm = rl.ECMClassifier(init='random')
ecm.fit(X_train)
ecm.predict(X_train)

with pytest.raises(KeyError):
ecm.m_probs['c_1'][0]

assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
assert math.isclose(ecm.p, 0.5, abs_tol=0.05) ```
Example #7
```def test_ecm_init_jaro_1value(self):

m = np.array([1.0, 0.85, .85, .81, .85, .81])
u = np.array([1.0, .10, .50, .23, .30, 0.13])

# Create the train dataset.
1000, 500, m=m, u=u, random_state=535, return_links=True)

ecm = rl.ECMClassifier(init='jaro')
ecm.fit(X_train)
ecm.predict(X_train)

with pytest.raises(KeyError):
ecm.m_probs['c_1'][0]

assert math.isclose(ecm.m_probs['c_1'][1], 1.0, abs_tol=0.01)
assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
assert math.isclose(ecm.u_probs['c_1'][1], 1.0, abs_tol=0.01)
assert math.isclose(ecm.u_probs['c_2'][1], 0.1, abs_tol=0.05)
assert math.isclose(ecm.p, 0.5, abs_tol=0.05) ```
Example #8
```def test_ecm_init_jaro_skewed(self):

m = np.array([1.0, 0.85, .85, .81, .85, .81])
u = np.array([0.0, .10, .50, .23, .30, 0.13])

# Create the train dataset.
1000, 500, m=m, u=u, random_state=535, return_links=True)

ecm = rl.ECMClassifier(init='jaro')
ecm.fit(X_train)
ecm.predict(X_train)

assert math.isclose(ecm.m_probs['c_1'][1], 1.0, abs_tol=0.01)
assert math.isclose(ecm.m_probs['c_2'][1], 0.85, abs_tol=0.08)
assert math.isclose(ecm.u_probs['c_1'][1], 0.0, abs_tol=0.01)
assert math.isclose(ecm.u_probs['c_2'][1], 0.1, abs_tol=0.05)
assert math.isclose(ecm.p, 0.5, abs_tol=0.05) ```
Example #9
```def test_ecm_init_jaro_inf(self):
m = np.array([0.95, .81, .85, .81, .85, .81])
u = np.array([0, .23, .50, .23, .30, 0.13])

# Create the train dataset.
10000, 500, m=m, u=u, random_state=535, return_links=True)

# Create the train dataset.
1000, 500, m=m, u=u, random_state=535, return_links=True)

ecm = rl.ECMClassifier()
ecm.fit(X_train)
ecm.predict(X_test)

assert math.isclose(ecm.u_probs['c_1'][1], 0.0, abs_tol=1e-3)
assert math.isclose(ecm.u_probs['c_1'][0], 1.0, abs_tol=1e-3) ```
Example #10
```def _test_float_point_number(self, type, byteorder):
float_value = uniform(-3.1415926535, 3.1415926535)

can_data = [0, 0]
configs = [{
"key": type + "Var",
"is_ts": True,
"type": type,
"start": len(can_data),
"length": 4 if type[0] == "f" else 8,
"byteorder": byteorder
}]

can_data.extend(_struct.pack((">" if byteorder[0] == "b" else "<") + type[0],
float_value))
tb_data = self.converter.convert(configs, can_data)
self.assertTrue(isclose(tb_data["telemetry"][type + "Var"], float_value, rel_tol=1e-05)) ```
Example #11
```def test_l2_low(self):

context = np.array([[1, 1, 0, 0, 1], [0, 1, 2, 9, 4], [2, 3, 1, 0, 2]])
rewards = np.array([3, 2, 1])
decisions = np.array([1, 1, 1])

arms, mab = self.predict(arms=[0, 1],
decisions=decisions,
rewards=rewards,
learning_policy=LearningPolicy.LinUCB(alpha=1, l2_lambda=0.1),
context_history=context,
contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
seed=123456,
num_run=1,
is_predict=True)

self.assertEqual(mab._imp.num_features, 5)
self.assertEqual(arms, [1, 1])
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[0], 1.59499705, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[1], -0.91856183, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[2], -2.49775977, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[3], 0.14219195, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[4], 1.65819347, abs_tol=0.00000001)) ```
Example #12
```def test_l2_high(self):

context = np.array([[1, 1, 0, 0, 1], [0, 1, 2, 9, 4], [2, 3, 1, 0, 2]])
rewards = np.array([3, 2, 1])
decisions = np.array([1, 1, 1])
arms, mab = self.predict(arms=[0, 1],
decisions=decisions,
rewards=rewards,
learning_policy=LearningPolicy.LinUCB(alpha=1, l2_lambda=10),
context_history=context,
contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
seed=123456,
num_run=1,
is_predict=True)

self.assertEqual(mab._imp.num_features, 5)
self.assertEqual(arms, [0, 0])
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[0], 0.18310155, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[1], 0.16372811, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[2], -0.00889076, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[3], 0.09434416, abs_tol=0.00000001))
self.assertTrue(math.isclose(mab._imp.arm_to_model[1].beta[4], 0.22503229, abs_tol=0.00000001)) ```
Example #13
```def test2_unused_arm(self):

arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 3, 3, 3, 3, 3],
rewards=[0, 1, 1, 0, 0, 0, 0, 1, 1, 1],
learning_policy=LearningPolicy.Softmax(tau=1),
seed=123456,
num_run=20,
is_predict=True)

self.assertTrue(4 in mab._imp.arm_to_expectation.keys())
self.assertEqual(arm[13], 4)

e_x = mab._imp.arm_to_exponent[4]
prob = mab._imp.arm_to_expectation[4]

self.assertTrue(math.isclose(e_x, 0.513, abs_tol=0.001))
self.assertTrue(math.isclose(prob, 0.173, abs_tol=0.001)) ```
Example #14
```def test_topic_delay(self):
average_delay_line_pattern = re.compile(r'average delay: (\d+.\d{3})')
stats_line_pattern = re.compile(
r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
)
with self.launch_topic_command(arguments=['delay', '/cmd_vel']) as topic_command:
assert topic_command.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
average_delay_line_pattern, stats_line_pattern
], strict=True
), timeout=10)
assert topic_command.wait_for_shutdown(timeout=10)

assert math.isclose(average_delay, 0.0, abs_tol=10e-3) ```
Example #15
```def test_topic_hz(self):
average_rate_line_pattern = re.compile(r'average rate: (\d+.\d{3})')
stats_line_pattern = re.compile(
r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
)
with self.launch_topic_command(arguments=['hz', '/chatter']) as topic_command:
assert topic_command.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
average_rate_line_pattern, stats_line_pattern
], strict=True
), timeout=10)
assert topic_command.wait_for_shutdown(timeout=10)

assert math.isclose(average_rate, 1., rel_tol=1e-2) ```
Example #16
```def test_filtered_topic_hz(self):
average_rate_line_pattern = re.compile(r'average rate: (\d+.\d{3})')
stats_line_pattern = re.compile(
r'\s*min: \d+.\d{3}s max: \d+.\d{3}s std dev: \d+.\d{5}s window: \d+'
)
with self.launch_topic_command(
arguments=[
'hz',
'--filter',
'int(m.data.rpartition(\":\")[-1]) % 2 == 0',
'/chatter'
]
) as topic_command:
assert topic_command.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
average_rate_line_pattern, stats_line_pattern
], strict=True
), timeout=10), 'Output does not match: ' + topic_command.output
assert topic_command.wait_for_shutdown(timeout=10)

assert math.isclose(average_rate, 0.5, rel_tol=1e-2) ```
Example #17
```def process_partition(partitionid, calls, ambigthresh=10):
passcalls = [c for c in calls if c.filterstr == 'PASS']
if len(passcalls) == 0:
return
maxscore = max([c.attribute('LIKESCORE') for c in passcalls])
maxcalls = list()
for c in calls:
passed = c.filterstr == 'PASS'
optimal = isclose(c.attribute('LIKESCORE'), maxscore)
if passed and optimal:
maxcalls.append(c)
else:
c.filter(kevlar.vcf.VariantFilter.PartitionScore)
for c in maxcalls:
if ambigthresh and len(maxcalls) > ambigthresh:
c.filter(kevlar.vcf.VariantFilter.AmbiguousCall)
else:
c.annotate('CALLCLASS', partitionid) ```
Example #18
```def test_doc_frequencies_example():
docs = [
list('abc'),
list('abb'),
list('ccc'),
list('da'),
]

abs_df = doc_frequencies(docs)
assert dict(abs_df) == {
'a': 3,
'b': 2,
'c': 2,
'd': 1,
}

rel_df = doc_frequencies(docs, proportions=True)
math.isclose(rel_df['a'], 3/4)
math.isclose(rel_df['b'], 2/4)
math.isclose(rel_df['c'], 2/4)
math.isclose(rel_df['d'], 1/4) ```
Example #19
```def paddle_bounce(self, paddle):
''' Changes ball's direction and curve when bouncing off the
self.x_direction_right = not self.x_direction_right
self.curved = True
else:
self.curved = False ```
Example #20
```def test_qval(left, right, alg):
for lib in libraries.get_libs(alg):
conditions = lib.conditions or {}
internal_func = getattr(textdistance, alg)(external=False, **conditions)
external_func = lib.get_function()
# algorithm doesn't support q-grams
if not hasattr(internal_func, 'qval'):
continue
for qval in (None, 1, 2, 3):
internal_func.qval = qval
# if qval unsopporting already set for lib
s1, s2 = internal_func._get_sequences(left, right)
if not lib.check_conditions(internal_func, s1, s2):
continue

# test
int_result = internal_func(left, right)
s1, s2 = lib.prepare(s1, s2)
ext_result = external_func(s1, s2)
assert isclose(int_result, ext_result), str(lib) ```
Example #21
```def test_ema_event_frequency_estimator_respects_reaction_time(step):
now = 0.0
half_time = 120.0
estimator = EMAEventFrequencyEstimator(now, half_time)
assert estimator.value == 0

while now < half_time:
estimator.update_time(now)
now += step
estimator.update_time(now)
assert math.isclose(estimator.value, 0.5, rel_tol=0.07)

while now < 2.0 * half_time:
estimator.update_time(now)
now += step
estimator.update_time(now)
assert math.isclose(estimator.value, 0.75, rel_tol=0.07) ```
Example #22
```def test_rsr_ema_throughput_measurement_creation():
tm = RevivalSpikeResistantEMAThroughputMeasurement(window_size=5,
min_cnt=9)

assert tm.window_size == 5
assert tm.min_cnt == 9
assert isclose(tm.alpha, 0.2)

assert tm.window_start_ts is None  # must not be initialized in `__init__`
assert tm.reqs_in_window == 0
assert tm.throughput == 0

assert tm.throughput_before_idle == 0
assert tm.idle_start_ts is None  # must not be initialized in `__init__`
assert tm.empty_windows_count == 0 ```
Example #23
```def test_rsr_ema_tm_throughput_in_normal_state(tm):
# [0, 15) - [225, 240) -- 16 not empty windows
for ts in range(0, 240, 5):

# [240, 255)
throughput_before = tm.get_throughput(240)
assert tm.state == State.NORMAL

for ts in range(240, 255, 1):  # load increases

# [255, 270)
throughput = tm.get_throughput(255)
assert tm.state == State.NORMAL

assert isclose(throughput,
(2 / 17) * 1 + (1 - 2 / 17) * throughput_before) ```
Example #24
```def floating_judge(a, b, tol=1e-6):
assert len(a) == len(b), "Length of the output and answer does not match"
for i in range(len(a)):
if not math.isclose(a[i], b[i], rel_tol=tol):
return False
return True ```
Example #25
```def test_internals(self):
assert self.scheduler.num_cycle_steps == 900
assert math.isclose(self.scheduler.final_lr, 0.1 * 0.01)
assert math.isclose(self.scheduler.get_lr(), 0.1)
assert math.isclose(self.scheduler.get_momentum(), 0.95) ```
Example #26
```def test_step(self):
# Scale up
for i in range(450):
self.scheduler.step()
assert self.scheduler.last_step == 450
assert math.isclose(self.scheduler.get_lr(), 1.)
assert math.isclose(self.scheduler.get_momentum(), 0.85)

# Scale down
for i in range(450):
self.scheduler.step()
assert self.scheduler.last_step == 900
assert math.isclose(self.scheduler.get_lr(), 0.1)
assert math.isclose(self.scheduler.get_momentum(), 0.95)

for i in range(100):
self.scheduler.step()
assert self.scheduler.last_step == 1000
assert math.isclose(self.scheduler.get_lr(), 0.001)
assert math.isclose(self.scheduler.get_momentum(), 0.95)

# Go beyond the given num of steps: check if it works okay
for i in range(50):
self.scheduler.step()
assert math.isclose(self.scheduler.get_lr(), 0.001)
assert math.isclose(self.scheduler.get_momentum(), 0.95) ```
Example #27
```def equals(a, b, float_tol=DEFAULT_FLOAT_TOL):
"""
Olympe own definition of equality between two values a and b.
For floats, just returns the result isclose(a, b, rel_tol=1e-7, abs_tol=1e-9).
For everything else, returns a == b.

Remark, for floats the 1e-7 relative tolerance is equivalent to a ~33cm delta for GPS
coordinates in decimal degrees.
"""
if isinstance(a, float) and isinstance(b, float):
rel_tol, abs_tol = float_tol
return isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
else:
return a == b ```
Example #28
```def is_epsg_datum(epsg):
# It looks like these are all in the 4000 to 42NN range.
# I can't determine which are valid, so I'm going to convert from meters to degrees
# If it's degrees to degrees, it won't modify the number
# The coordinate systems we will look for are limited between -180.0 and 180.0 output
meter_proj = pyproj.Proj(init='epsg:'+str(epsg), preserve_units=False) # Forces meter
degree_proj = pyproj.Proj(proj='latlong', datum='WGS84')
try:
scale_value = 1.0e6
x2, y2 = pyproj.transform(meter_proj, degree_proj, scale_value, 0.0)
return math.isclose(scale_value, x2, abs_tol=1.0) # Should be very different
except:
pass
return True # Invalidate this EPSG if it can't be determined or used ```
Example #29
```def test_fit_twice(self):

arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 3, 3, 3, 3, 3],
rewards=[0, 0, 1, 0, 0, 0, 0, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
seed=123456,
num_run=1,
is_predict=True)

self.assertEqual(arm, [4, 4])

b_1 = mab._imp.arm_to_model[1].beta
self.assertTrue(math.isclose(-0.0825688, b_1[0], abs_tol=0.00001))

b_3 = mab._imp.arm_to_model[3].beta
self.assertTrue(math.isclose(0.023696, b_3[0], abs_tol=0.00001))

self.assertTrue(4 in mab._imp.arm_to_model.keys())

# Fit again
decisions2 = [1, 3, 4]
rewards2 = [0, 1, 1]
context_history2 = [[0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0]]
mab.fit(decisions2, rewards2, context_history2)

b_1 = mab._imp.arm_to_model[1].beta
self.assertEqual(b_1[0], 0)

b_3 = mab._imp.arm_to_model[3].beta
self.assertTrue(math.isclose(b_3[0], 0.16667, abs_tol=0.00001))

b_4 = mab._imp.arm_to_model[4].beta
self.assertEqual(b_4[0], 0) ```
Example #30
```def test_partial_fit(self):

arm, mab = self.predict(arms=[1, 2, 3, 4],
decisions=[1, 1, 1, 2, 2, 3, 3, 3, 3, 3],
rewards=[0, 0, 1, 0, 0, 0, 0, 1, 1, 1],
learning_policy=LearningPolicy.LinUCB(alpha=1),
context_history=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0],
[0, 2, 2, 3, 5], [1, 3, 1, 1, 1], [0, 0, 0, 0, 0],
[0, 1, 4, 3, 5], [0, 1, 2, 4, 5], [1, 2, 1, 1, 3],
[0, 2, 1, 0, 0]],
contexts=[[0, 1, 2, 3, 5], [1, 1, 1, 1, 1]],
seed=123456,
num_run=1,
is_predict=True)

self.assertEqual(arm, [4, 4])

b_1 = mab._imp.arm_to_model[1].beta
self.assertTrue(math.isclose(-0.0825688, b_1[0], abs_tol=0.00001))

b_3 = mab._imp.arm_to_model[3].beta
self.assertTrue(math.isclose(0.023696, b_3[0], abs_tol=0.00001))

self.assertTrue(4 in mab._imp.arm_to_model.keys())

# Fit again
decisions2 = [1, 3, 4]
rewards2 = [0, 1, 1]
context_history2 = [[0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0]]
mab.partial_fit(decisions2, rewards2, context_history2)

b_1 = mab._imp.arm_to_model[1].beta
self.assertTrue(math.isclose(-0.05142857, b_1[0], abs_tol=0.00001))

b_3 = mab._imp.arm_to_model[3].beta
self.assertTrue(math.isclose(b_3[0], 0.22099152, abs_tol=0.00001))

b_4 = mab._imp.arm_to_model[4].beta
self.assertEqual(b_4[0], 0) ```