Python math.fabs() Examples
The following are 30
code examples of math.fabs().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
math
, or try the search function
.
Example #1
Source File: Brent.py From Finance-Python with MIT License | 6 votes |
def nextX(self): if self.c[1] != self.a[1] and self.c[1] != self.b[1]: # inverse quadratic interpolation s = self.a[0] * self.b[1] * self.c[1] / ((self.a[1] - self.b[1]) * (self.a[1] - self.c[1])) \ + self.b[0] * self.a[1] * self.c[1] / ((self.b[1] - self.a[1]) * (self.b[1] - self.c[1])) \ + self.c[0] * self.a[1] * self.b[1] / ((self.c[1] - self.a[1]) * (self.c[1] - self.b[1])) else: s = (self.a[0] * self.b[1] - self.b[0] * self.a[1]) / (self.b[1] - self.a[1]) c_dist = fabs(self.c[0] - self.b[0] if self.bisect else self.d) self.bisect = (s - self.b[0]) * (s - 0.75 * self.a[0] - 0.25 * self.b[0]) >= 0. \ or fabs(s - self.b[0]) > 0.5 * c_dist \ or c_dist < self.tol if self.bisect: s = 0.5 * (self.a[0] + self.b[0]) self.d = s return s
Example #2
Source File: schwefel.py From NiaPy with MIT License | 6 votes |
def function(self): r"""Return benchmark evaluation function. Returns: Callable[[int, Union[int, float, List[int, float], numpy.ndarray]], float]: Fitness function """ def g(z, D): if z > 500: return (500 - fmod(z, 500)) * sin(sqrt(fabs(500 - fmod(z, 500)))) - (z - 500) ** 2 / (10000 * D) elif z < -500: return (fmod(z, 500) - 500) * sin(sqrt(fabs(fmod(z, 500) - 500))) + (z - 500) ** 2 / (10000 * D) return z * sin(fabs(z) ** (1 / 2)) def h(x, D): return g(x + 420.9687462275036, D) def f(D, sol): r"""Fitness function. Args: D (int): Dimensionality of the problem sol (Union[int, float, List[int, float], numpy.ndarray]): Solution to check. Returns: float: Fitness value for the solution. """ val = 0.0 for i in range(D): val += h(sol[i], D) return 418.9829 * D - val return f
Example #3
Source File: sphere.py From sphere with MIT License | 6 votes |
def contains(self, other): if isinstance(other, self.__class__): if self.is_inverted(): if other.is_inverted(): return other.lo() >= self.lo() and other.hi() <= self.hi() return (other.lo() >= self.lo() or other.hi() <= self.hi()) \ and not self.is_empty() else: if other.is_inverted(): return self.is_full() or other.is_empty() return other.lo() >= self.lo() and other.hi() <= self.hi() else: assert math.fabs(other) <= math.pi if other == -math.pi: other = math.pi return self.fast_contains(other)
Example #4
Source File: test_pySmartDL.py From pySmartDL with The Unlicense | 6 votes |
def test_speed_limiting(self): obj = pySmartDL.SmartDL(self.res_testfile_1gb, dest=self.dl_dir, progress_bar=False, connect_default_logger=self.enable_logging) obj.limit_speed(1024**2) # 1MB per sec obj.start(blocking=False) while not obj.get_dl_size(): time.sleep(0.1) time.sleep(30) expected_dl_size = 30 * 1024**2 allowed_delta = 0.6 # because we took only 30sec, the delta needs to be quite big, it we were to test 60sec the delta would probably be much smaller diff = math.fabs(expected_dl_size - obj.get_dl_size()) / expected_dl_size obj.stop() obj.wait() self.assertLessEqual(diff, allowed_delta)
Example #5
Source File: gripper_action_server.py From AI-Robot-Challenge-Lab with MIT License | 6 votes |
def check_success(self, position, close_goal): rospy.logwarn("gripping force: " + str(self._gripper.get_force())) rospy.logwarn("gripper position: " + str(self._gripper.get_position())) rospy.logwarn("gripper position deadzone: " + str(self._gripper.get_dead_zone())) if not self._gripper.is_moving(): success = True else: success = False # success = fabs(self._gripper.get_position() - position) < self._gripper.get_dead_zone() rospy.logwarn("gripping success: " + str(success)) return success
Example #6
Source File: heightmap.py From hexgen with GNU General Public License v3.0 | 6 votes |
def _adjust(self, xa, ya, x, y, xb, yb): """ fix the sides of the map """ if self.grid[x][y] == 0: d = math.fabs(xa - xb) + math.fabs(ya - yb) ROUGHNESS = self.params.get('roughness') v = (self.grid[xa][ya] + self.grid[xb][yb]) / 2.0 \ + (random.random() - 0.5) * d * ROUGHNESS c = int(math.fabs(v) % 257) if y == 0: self.grid[x][self.size - 1] = c if x == 0 or x == self.size - 1: if y < self.size - 1: self.grid[x][self.size - 1 - y] = c range_low, range_high = self.params.get('height_range') if c < range_low: c = range_low elif c > range_high: c = range_high self.grid[x][y] = c
Example #7
Source File: hgbat.py From NiaPy with MIT License | 6 votes |
def function(self): r"""Return benchmark evaluation function. Returns: Callable[[int, Union[int, float, List[int, float], numpy.ndarray]], float]: Fitness function """ def f(D, x): r"""Fitness function. Args: D (int): Dimensionality of the problem sol (Union[int, float, List[int, float], numpy.ndarray]): Solution to check. Returns: float: Fitness value for the solution. """ val1, val2 = 0.0, 0.0 for i in range(D): val1 += x[i] ** 2 for i in range(D): val2 += x[i] return fabs(val1 ** 2 - val2 ** 2) ** (1 / 2) + (0.5 * val1 + val2) / D + 0.5 return f # vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
Example #8
Source File: katsuura.py From NiaPy with MIT License | 6 votes |
def function(self): r"""Return benchmark evaluation function. Returns: Callable[[int, Union[int, float, List[int, float], numpy.ndarray]], float]: Fitness function """ def f(D, x): r"""Fitness function. Args: D (int): Dimensionality of the problem sol (Union[int, float, List[int, float], numpy.ndarray]): Solution to check. Returns: float: Fitness value for the solution. """ val = 1.0 for i in range(D): valt = 1.0 for j in range(1, 33): valt += fabs(2 ** j * x[i] - round(2 ** j * x[i])) / 2 ** j val *= (1 + (i + 1) * valt) ** (10 / D ** 1.2) - (10 / D ** 2) return 10 / D ** 2 * val return f # vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3
Example #9
Source File: intelc.py From arnold-usd with Apache License 2.0 | 6 votes |
def get_version_from_list(v, vlist): """See if we can match v (string) in vlist (list of strings) Linux has to match in a fuzzy way.""" if is_windows: # Simple case, just find it in the list if v in vlist: return v else: return None else: # Fuzzy match: normalize version number first, but still return # original non-normalized form. fuzz = 0.001 for vi in vlist: if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz: return vi # Not found return None
Example #10
Source File: test_util.py From lambda-packs with MIT License | 6 votes |
def assertNear(self, f1, f2, err, msg=None): """Asserts that two floats are near each other. Checks that |f1 - f2| < err and asserts a test failure if not. Args: f1: A float value. f2: A float value. err: A float value. msg: An optional string message to append to the failure message. """ self.assertTrue( math.fabs(f1 - f2) <= err, "%f != %f +/- %f%s" % (f1, f2, err, " (%s)" % msg if msg is not None else ""))
Example #11
Source File: test_meters.py From tnt with BSD 3-Clause "New" or "Revised" License | 6 votes |
def testAUCMeter(self): mtr = meter.AUCMeter() test_size = 1000 mtr.add(torch.rand(test_size), torch.zeros(test_size)) mtr.add(torch.rand(test_size), torch.Tensor(test_size).fill_(1)) val, tpr, fpr = mtr.value() self.assertTrue(math.fabs(val - 0.5) < 0.1, msg="AUC Meter fails") mtr.reset() mtr.add(torch.Tensor(test_size).fill_(0), torch.zeros(test_size)) mtr.add(torch.Tensor(test_size).fill_(0.1), torch.zeros(test_size)) mtr.add(torch.Tensor(test_size).fill_(0.2), torch.zeros(test_size)) mtr.add(torch.Tensor(test_size).fill_(0.3), torch.zeros(test_size)) mtr.add(torch.Tensor(test_size).fill_(0.4), torch.zeros(test_size)) mtr.add(torch.Tensor(test_size).fill_(1), torch.Tensor(test_size).fill_(1)) val, tpr, fpr = mtr.value() self.assertEqual(val, 1.0, msg="AUC Meter fails")
Example #12
Source File: intelc.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
def get_version_from_list(v, vlist): """See if we can match v (string) in vlist (list of strings) Linux has to match in a fuzzy way.""" if is_windows: # Simple case, just find it in the list if v in vlist: return v else: return None else: # Fuzzy match: normalize version number first, but still return # original non-normalized form. fuzz = 0.001 for vi in vlist: if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz: return vi # Not found return None
Example #13
Source File: Brent.py From Finance-Python with MIT License | 5 votes |
def bracketWidth(self): return fabs(self.a[0] - self.b[0])
Example #14
Source File: Brent.py From Finance-Python with MIT License | 5 votes |
def initialize(self, low, high): self.a = low self.b = high pyFinAssert(self.a[1] * self.b[1] <= 0., ValueError, 'root is not bracketed') if fabs(self.a[1]) < fabs(self.b[1]): self.a, self.b = self.b, self.a self.c = self.a self.bisect = True self.d = 0
Example #15
Source File: utilities.py From Finance-Python with MIT License | 5 votes |
def check_converge(self, root_finder, e): root_finder.putY(e) return fabs(e) < self.f_tol or root_finder.bracketWidth() < self.x_tol
Example #16
Source File: dataset_utils.py From rpg_davis_simulator with GNU General Public License v3.0 | 5 votes |
def find_closest_id(self, t): idx = np.searchsorted(self.t, t, side="left") if fabs(t - self.t[idx-1]) < fabs(t - self.t[idx]): return idx-1 else: return idx
Example #17
Source File: dlav0.py From centerpose with MIT License | 5 votes |
def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :]
Example #18
Source File: shufflenetv2_dcn.py From centerpose with MIT License | 5 votes |
def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :]
Example #19
Source File: pose_dla_dcn.py From centerpose with MIT License | 5 votes |
def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :]
Example #20
Source File: mobilenetv3.py From centerpose with MIT License | 5 votes |
def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :]
Example #21
Source File: mobilenetv2.py From centerpose with MIT License | 5 votes |
def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :]
Example #22
Source File: simple_vehicle_control.py From scenario_runner with MIT License | 5 votes |
def _set_new_velocity(self, next_location): """ Calculate and set the new actor veloctiy given the current actor location and the _next_location_ Args: next_location (carla.Location): Next target location of the actor returns: direction (carla.Vector3D): Normalized direction vector of the actor """ # set new linear velocity velocity = carla.Vector3D(0, 0, 0) direction = next_location - CarlaDataProvider.get_location(self._actor) direction_norm = math.sqrt(direction.x**2 + direction.y**2) velocity.x = direction.x / direction_norm * self._target_speed velocity.y = direction.y / direction_norm * self._target_speed self._actor.set_velocity(velocity) # set new angular velocity current_yaw = CarlaDataProvider.get_transform(self._actor).rotation.yaw new_yaw = CarlaDataProvider.get_map().get_waypoint(next_location).transform.rotation.yaw delta_yaw = new_yaw - current_yaw if math.fabs(delta_yaw) > 360: delta_yaw = delta_yaw % 360 if delta_yaw > 180: delta_yaw = delta_yaw - 360 elif delta_yaw < -180: delta_yaw = delta_yaw + 360 angular_velocity = carla.Vector3D(0, 0, 0) angular_velocity.z = delta_yaw / (direction_norm / self._target_speed) self._actor.set_angular_velocity(angular_velocity) return direction_norm
Example #23
Source File: test_util.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def assertNear(self, f1, f2, err, msg=None): """Asserts that two floats are near each other. Checks that |f1 - f2| < err and asserts a test failure if not. Args: f1: A float value. f2: A float value. err: A float value. msg: An optional string message to append to the failure message. """ self.assertTrue(math.fabs(f1 - f2) <= err, "%f != %f +/- %f%s" % ( f1, f2, err, " (%s)" % msg if msg is not None else ""))
Example #24
Source File: codec.py From polyline with MIT License | 5 votes |
def _py2_round(self, x): # The polyline algorithm uses Python 2's way of rounding return int(math.copysign(math.floor(math.fabs(x) + 0.5), x))
Example #25
Source File: sphere.py From sphere with MIT License | 5 votes |
def intersects_lat_edge(cls, a, b, lat, lon): assert is_unit_length(a) assert is_unit_length(b) z = robust_cross_prod(a, b).normalize() if z[2] < 0: z = -z y = robust_cross_prod(z, Point(0, 0, 1)).normalize() x = y.cross_prod(z) assert is_unit_length(x) assert x[2] >= 0 sin_lat = math.sin(lat) if math.fabs(sin_lat) >= x[2]: return False assert x[2] > 0 cos_theta = sin_lat / x[2] sin_theta = math.sqrt(1 - cos_theta * cos_theta) theta = math.atan2(sin_theta, cos_theta) ab_theta = SphereInterval.from_point_pair( math.atan2(a.dot_prod(y), a.dot_prod(x)), math.atan2(b.dot_prod(y), b.dot_prod(x))) if ab_theta.contains(theta): isect = x * cos_theta + y * sin_theta if lon.contains(math.atan2(isect[1], isect[0])): return True if ab_theta.contains(-theta): isect = x * cos_theta - y * sin_theta if lon.contains(math.atan2(isect[1], isect[0])): return True return False
Example #26
Source File: test_math.py From ironpython2 with Apache License 2.0 | 5 votes |
def testFabs(self): self.assertRaises(TypeError, math.fabs) self.ftest('fabs(-1)', math.fabs(-1), 1) self.ftest('fabs(0)', math.fabs(0), 0) self.ftest('fabs(1)', math.fabs(1), 1)
Example #27
Source File: random_prices.py From winton-kafka-streams with Apache License 2.0 | 5 votes |
def next_price(self): """Calculate and return a new price; use initial price on first call""" if self._state.iter == 0: # On first iteration use initial price price = self._initial_price else: change = self._state.random.gauss(0.0, self._sigma) price = _fabs( self._state.last_price + self._state.last_price * change ) if price < 0.1: price = 0.1 self._state = _STATE(price, self._state.random, self._state.iter + 1) return self._state.last_price
Example #28
Source File: vader.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def _sift_sentiment_scores(self, sentiments): # want separate positive versus negative sentiment scores pos_sum = 0.0 neg_sum = 0.0 neu_count = 0 for sentiment_score in sentiments: if sentiment_score > 0: pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1 if sentiment_score < 0: neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals if sentiment_score == 0: neu_count += 1 return pos_sum, neg_sum, neu_count
Example #29
Source File: vader.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def score_valence(self, sentiments, text): if sentiments: sum_s = float(sum(sentiments)) # compute and add emphasis from punctuation in text punct_emph_amplifier = self._punctuation_emphasis(sum_s, text) if sum_s > 0: sum_s += punct_emph_amplifier elif sum_s < 0: sum_s -= punct_emph_amplifier compound = normalize(sum_s) # discriminate between positive, negative and neutral sentiment scores pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments) if pos_sum > math.fabs(neg_sum): pos_sum += (punct_emph_amplifier) elif pos_sum < math.fabs(neg_sum): neg_sum -= (punct_emph_amplifier) total = pos_sum + math.fabs(neg_sum) + neu_count pos = math.fabs(pos_sum / total) neg = math.fabs(neg_sum / total) neu = math.fabs(neu_count / total) else: compound = 0.0 pos = 0.0 neg = 0.0 neu = 0.0 sentiment_dict = \ {"neg" : round(neg, 3), "neu" : round(neu, 3), "pos" : round(pos, 3), "compound" : round(compound, 4)} return sentiment_dict
Example #30
Source File: minitaur_four_leg_stand_env.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def _reward(self): roll, pitch, _ = self.minitaur.GetBaseRollPitchYaw() return 1.0 / (0.001 + math.fabs(roll) + math.fabs(pitch))