Python math.fabs() Examples

The following are 30 code examples for showing how to use math.fabs(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 6 votes vote down vote up
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 2
Project: pySmartDL   Author: iTaybb   File: test_pySmartDL.py    License: The Unlicense 6 votes vote down vote up
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 3
Project: AI-Robot-Challenge-Lab   Author: microsoft   File: gripper_action_server.py    License: MIT License 6 votes vote down vote up
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 4
Project: hexgen   Author: eranimo   File: heightmap.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: NiaPy   Author: NiaOrg   File: hgbat.py    License: MIT License 6 votes vote down vote up
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 6
Project: NiaPy   Author: NiaOrg   File: katsuura.py    License: MIT License 6 votes vote down vote up
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 7
Project: NiaPy   Author: NiaOrg   File: schwefel.py    License: MIT License 6 votes vote down vote up
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 8
Project: arnold-usd   Author: Autodesk   File: intelc.py    License: Apache License 2.0 6 votes vote down vote up
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 9
Project: lambda-packs   Author: ryfeus   File: test_util.py    License: MIT License 6 votes vote down vote up
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 10
Project: tnt   Author: pytorch   File: test_meters.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 11
Project: web2board   Author: bq   File: intelc.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 12
Project: Finance-Python   Author: alpha-miner   File: Brent.py    License: MIT License 6 votes vote down vote up
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 13
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_trotting_env.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_fallen(self):
    """Decide whether the minitaur has fallen.

    Returns:
      Boolean value that indicates whether the minitaur has fallen.
    """
    roll, pitch, _ = self.minitaur.GetTrueBaseRollPitchYaw()
    is_fallen = math.fabs(roll) > 0.3 or math.fabs(pitch) > 0.3
    return is_fallen 
Example 14
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_reactive_env.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_fallen(self):
    """Decides whether the minitaur is in a fallen state.

    If the roll or the pitch of the base is greater than 0.3 radians, the
    minitaur is considered fallen.

    Returns:
      Boolean value that indicates whether the minitaur has fallen.
    """
    roll, pitch, _ = self.minitaur.GetTrueBaseRollPitchYaw()
    return math.fabs(roll) > 0.3 or math.fabs(pitch) > 0.3 
Example 15
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_four_leg_stand_env.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _reward(self):
    roll, pitch, _ = self.minitaur.GetBaseRollPitchYaw()
    return 1.0 / (0.001 + math.fabs(roll) + math.fabs(pitch)) 
Example 16
Project: razzy-spinner   Author: rafasashi   File: vader.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 17
Project: razzy-spinner   Author: rafasashi   File: vader.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 18
Project: worker   Author: moira-alert   File: functions.py    License: GNU General Public License v3.0 5 votes vote down vote up
def holtWintersDeviation(gamma, actual, prediction, last_seasonal_dev):
    if prediction is None:
        prediction = 0
    return gamma * math.fabs(actual - prediction) + \
        (1 - gamma) * last_seasonal_dev 
Example 19
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def abs(self):
        return self.__class__(math.fabs(self.__point[0]),
                                math.fabs(self.__point[1]),
                                math.fabs(self.__point[2])) 
Example 20
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-15):
        return math.fabs(self.lat().radians - other.lat().radians) \
                < max_error and \
            math.fabs(self.lon().radians - other.lon().radians) < max_error 
Example 21
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-14):
        return (self.axis().angle(other.axis()) <= max_error \
                and math.fabs(self.height() - other.height()) <= max_error) \
                or (self.is_empty() and other.height() <= max_error) \
                or (other.is_empty() and self.height() <= max_error) \
                or (self.is_full() and other.height() >= 2 - max_error) \
                or (other.is_full() and self.height() >= 2 - max_error) 
Example 22
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def is_valid(self):
        return math.fabs(self.lat().lo()) <= math.pi / 2.0 \
                and math.fabs(self.lat().hi()) <= math.pi / 2.0 \
                and self.lon().is_valid() \
                and self.lat().is_empty() == self.lon().is_empty() 
Example 23
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
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 24
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-15):
        if self.is_empty():
            return other.get_length() <= max_error
        if other.is_empty():
            return self.get_length() <= max_error
        return math.fabs(other.lo() - self.lo()) \
                + math.fabs(other.hi() - self.hi()) <= max_error

# originally S1Interval in C++ code 
Example 25
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def from_point_pair(cls, a, b):
        assert math.fabs(a) <= math.pi
        assert math.fabs(b) <= math.pi
        if a == -math.pi:
            a = math.pi
        if b == -math.pi:
            b = math.pi
        if cls.positive_distance(a, b) <= math.pi:
            return cls(a, b, args_checked=True)
        else:
            return cls(b, a, args_checked=True) 
Example 26
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def is_valid(self):
        return math.fabs(self.lo()) <= math.pi \
                and math.fabs(self.hi()) <= math.pi \
                and not (self.lo() == -math.pi and self.hi() != math.pi) \
                and not (self.hi() == -math.pi and self.lo() != math.pi) 
Example 27
Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-15):
        if self.is_empty():
            return other.get_length() <= max_error
        if other.is_empty():
            return self.get_length() <= max_error
        return (math.fabs(drem(other.lo() - self.lo(), 2 * math.pi)) \
            + math.fabs(drem(other.hi() - self.hi(), 2 * math.pi))) <= max_error 
Example 28
Project: sphere   Author: qedus   File: sphere_test.py    License: MIT License 5 votes vote down vote up
def testGetLength(self):
        self.assertEqual(self.quad12.get_length(), math.pi)
        self.assertEqual(self.pi.get_length(), 0)
        self.assertEqual(self.mipi.get_length(), 0)
        self.assertEqual(self.quad123.get_length(), 1.5 * math.pi)
        self.assertEqual(math.fabs(self.quad23.get_length()), math.pi)
        self.assertEqual(self.full.get_length(), 2 * math.pi)
        self.assertLess(self.empty.get_length(), 0) 
Example 29
Project: pykaldi   Author: pykaldi   File: kaldi-math-test.py    License: Apache License 2.0 5 votes vote down vote up
def testDefines(self):
        self.assertAlmostEqual(0.0, kaldi_math.exp(kaldi_math.LOG_ZERO_FLOAT))
        self.assertAlmostEqual(0.0, kaldi_math.exp(kaldi_math.LOG_ZERO_DOUBLE))

        # TODO:
        # How to test these in Python?

        # den = 0.0
        # self.assertTrue(kaldi_math.KALDI_ISNAN(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISINF(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISFINITE(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISNAN(1.0 / den))
        # self.assertTrue(kaldi_math.KALDI_ISINF(1.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISFINITE(1.0 / den))
        # self.assertTrue(kaldi_math.KALDI_ISFINITE(0.0))
        # self.assertFalse(kaldi_math.KALDI_ISINF(0.0))
        # self.assertFalse(kaldi_math.KALDI_ISNAN(0.0))


        self.assertTrue(1.0 != 1.0 + kaldi_math.DBL_EPSILON)
        self.assertTrue(1.0 == 1.0 + 0.5 * kaldi_math.DBL_EPSILON)
        # self.assertNotAlmostEqual(1.0, 1.0 + kaldi_math.FLT_EPSILON, places = 7)
        # self.assertAlmostEqual(1.0, 1.0 + 0.5 * kaldi_math.FLT_EPSILON, places = 6)

        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.M_PI)))
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.M_PI)))
        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.M_2PI)))
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.M_2PI)))

        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.exp(kaldi_math.M_LOG_2PI))), places = 5)
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.exp(kaldi_math.M_LOG_2PI))), places = 5) 
Example 30
Project: Python-John-Zelle-book   Author: sai29   File: 9.py    License: MIT License 5 votes vote down vote up
def main():
	year = int(raw_input("Enter the year: "))


	if year >= 1900 and year <= 2099 and year != 1954 and year != 1981 and year != 2049 and year != 2076:
		a = (year % 19 )
		b = (year % 4)
		c = (year % 7)
		d = (19 * a + 24) % 30
		e = (2*b + 4*c + 6*d + 5) % 7
		date = 22 + d + e
		date1 = d + e
		print date1
		if date1 < 9:
			print "Easter is on March %d" %(date)

		elif date1 > 9:
			date = 22 + d + e
			date2 = 31 - date
			date3 = math.fabs(date2)
			print "Easter is on April %d" %(date3)
	else :
		a = (year % 19 )
		b = (year % 4)
		c = (year % 7)
		d = (19 * a + 24) % 30
		e = (2*b + 4*c + 6*d + 5) % 7
		date = 22 + d + e
		date1 = d + e
		print date1
		if date1 < 9:
			print "Easter is on March %d" %(date)

		elif date1 > 9:
			date = 22 + d + e
			date2 = 31 - date + 7
			date3 = math.fabs(date2)
			print "Easter is on April %d" %(date3)