当前位置: 首页>>代码示例>>Python>>正文


Python math.isinf函数代码示例

本文整理汇总了Python中math.isinf函数的典型用法代码示例。如果您正苦于以下问题:Python isinf函数的具体用法?Python isinf怎么用?Python isinf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了isinf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PureStrategyDominance

def PureStrategyDominance(game, conditional=True, weak=False):
	"""
	pure-strategy dominance criterion for IEDS

	conditional==0==False --> unconditional dominance
	conditional==1==True ---> conditional dominance
	conditional==2 ---------> extra-conservative conditional dominance
	"""
	undominated = {r:set(game.strategies[r]) for r in game.roles}
	for r in game.roles:
		for dominant, dominated in product(game.strategies[r], repeat=2):
			if dominant == dominated or dominated not in undominated[r]:
				continue
			dominance_proved = False
			for profile in game:
				if dominated in profile[r]:
					reg = regret(game, profile, r, dominated, dominant)
					if reg > 0 and not isinf(reg):
						dominance_proved = True
					elif (reg < 0) or (reg == 0 and not weak) or \
							(isinf(reg) and conditional):
						dominance_proved = False
						break
				elif dominant in profile[r] and conditional > 1:
					if profile.deviate(r, dominant, dominated) not in game:
						dominance_proved = False
						break
			if dominance_proved:
				undominated[r].remove(dominated)
	return Subgame(game, undominated)
开发者ID:augie,项目名称:egats,代码行数:30,代码来源:Dominance.py

示例2: xsString

def xsString(xc, p, source):
    if isinstance(source,bool):
        return 'true' if source else 'false'
    elif isinstance(source,float):
        if isnan(source):
            return "NaN"
        elif isinf(source):
            return "INF"
        '''
        numMagnitude = fabs(source)
        if numMagnitude < 1000000 and numMagnitude > .000001:
            # don't want floating notation which python does for more than 4 decimal places
            s = 
        '''
        s = str(source)
        if s.endswith(".0"):
            s = s[:-2]
        return s
    elif isinstance(source,Decimal):
        if isnan(source):
            return "NaN"
        elif isinf(source):
            return "INF"
        return str(source)
    elif isinstance(source,ModelValue.DateTime):
        return ('{0:%Y-%m-%d}' if source.dateOnly else '{0:%Y-%m-%dT%H:%M:%S}').format(source)
    return str(source)
开发者ID:acsone,项目名称:Arelle,代码行数:27,代码来源:FunctionXs.py

示例3: test_pow

    def test_pow(self):
        import math

        def pw(x, y):
            return x ** y
        def espeq(x, y):
            return not abs(x-y) > 1e05
        raises(ZeroDivisionError, pw, 0.0, -1)
        assert pw(0, 0.5) == 0.0
        assert espeq(pw(4.0, 0.5), 2.0)
        assert pw(4.0, 0) == 1.0
        assert pw(-4.0, 0) == 1.0
        assert type(pw(-1.0, 0.5)) == complex
        assert pw(-1.0, 2.0) == 1.0
        assert pw(-1.0, 3.0) == -1.0
        assert pw(-1.0, 1e200) == 1.0
        if self.py26:
            assert pw(0.0, float("-inf")) == float("inf")
            assert math.isnan(pw(-3, float("nan")))
            assert math.isnan(pw(-3., float("nan")))
            assert pw(-1.0, -float('inf')) == 1.0
            assert pw(-1.0, float('inf')) == 1.0
            assert pw(float('inf'), 0) == 1.0
            assert pw(float('nan'), 0) == 1.0

            assert math.isinf(pw(-0.5, float('-inf')))
            assert math.isinf(pw(+0.5, float('-inf')))
            assert pw(-1.5, float('-inf')) == 0.0
            assert pw(+1.5, float('-inf')) == 0.0

            assert str(pw(float('-inf'), -0.5)) == '0.0'
            assert str(pw(float('-inf'), -2.0)) == '0.0'
            assert str(pw(float('-inf'), -1.0)) == '-0.0'
            assert str(pw(float('-inf'), 1.0)) == '-inf'
            assert str(pw(float('-inf'), 2.0)) == 'inf'
开发者ID:Qointum,项目名称:pypy,代码行数:35,代码来源:test_floatobject.py

示例4: isclose

    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))
开发者ID:katdev,项目名称:IntroPython2015,代码行数:35,代码来源:test_trapz.py

示例5: combine_rshift

def combine_rshift(range1, range2):
    """
    Combiner for Right shift operation.

    >>> import ast
    >>> combine(Range(10, 100), Range(3, 8), ast.RShift())
    Range(low=0, high=12)
    >>> combine(Range(10, float("inf")), Range(3, 8),
    ...                       ast.RShift())
    Range(low=0, high=inf)
    >>> combine(Range(-float("inf"), 0), Range(3, 8),
    ...                       ast.RShift())
    Range(low=-inf, high=0)
    >>> combine(Range(-30, 10), Range(3, float('inf')),
    ...                       ast.RShift())
    Range(low=-4, high=1)
    """
    if range1.low <= 0:
        if isinf(range1.low):
            min_ = range1.low
        else:
            min_ = range1.low >> range2.low
    elif isinf(range2.high):
        min_ = 0
    else:
        min_ = range1.low >> range2.high
    if isinf(range1.high):
        max_ = range1.high
    elif isinf(range2.low):
        max_ = 0
    else:
        max_ = range1.high >> range2.low
    return Range(min_, max_)
开发者ID:jfinkels,项目名称:pythran,代码行数:33,代码来源:range.py

示例6: retreive_WMS_metadata

    def retreive_WMS_metadata(typename):
        workspace, layername = decodeTypeName(typename)

        # workspace is hard-coded in the importer
        url = settings.OGC_SERVER['default']['LOCATION'] + workspace+"/"
        url += layername + "/wms?request=GetCapabilities&version=1.1.1"

        get_cap_data = CreateStoryLayerThumbnailTask.request_geoserver_with_credentials(
            url)
        wms = WebMapService(url, xml=get_cap_data)

        # I found that some dataset advertise illegal bounds - fix them up
        xmin = wms[layername].boundingBoxWGS84[0]
        if math.isnan(xmin) or math.isinf(xmin) or xmin < -180:
            xmin = -180

        ymin = wms[layername].boundingBoxWGS84[1]
        if math.isnan(ymin) or math.isinf(ymin) or ymin < -90:
            ymin = -90

        xmax = wms[layername].boundingBoxWGS84[2]
        if math.isnan(xmax) or math.isinf(xmax) or xmax > 180:
            xmax = 180

        ymax = wms[layername].boundingBoxWGS84[3]
        if math.isnan(ymax) or math.isinf(ymax) or ymax > 90:
            ymax = 90

        return [xmin, ymin, xmax, ymax], wms[layername].timepositions
开发者ID:lhcramer,项目名称:mapstory,代码行数:29,代码来源:tasks.py

示例7: toVector

    def toVector(longitude, latitude):
        """Converts a set of spherical coordinates to a 3-vector.

        The conversion shall not be performed by any library, to ensure
        that the test case does not duplicate the code being tested.

        Parameters
        ----------
        longitude : `Angle`
            The longitude (right ascension, azimuth, etc.) of the
            position.
        latitude : `Angle`
            The latitude (declination, elevation, etc.) of the
            position.

        Returns
        -------
        x, y, z : `number`
            Components of the unit vector representation of
            `(longitude, latitude)`
        """
        alpha = longitude.asRadians()
        delta = latitude.asRadians()
        if math.isnan(alpha) or math.isinf(alpha) or math.isnan(delta) or math.isinf(delta):
            return (nan, nan, nan)

        x = math.cos(alpha)*math.cos(delta)
        y = math.sin(alpha)*math.cos(delta)
        z = math.sin(delta)
        return (x, y, z)
开发者ID:HyperSuprime-Cam,项目名称:geom,代码行数:30,代码来源:test_spherePoint.py

示例8: parallel_line2d

def parallel_line2d(m, b, d):
    b_ = None
    if math.isinf(m) or math.isinf(-m):
        b_ = d
    else:
        b_ = b + d * math.sqrt(m * m + 1)
    return m, b_
开发者ID:openlmd,项目名称:robpath,代码行数:7,代码来源:calculate.py

示例9: add_point

    def add_point(self, label, pos, setpos, dmin, dmax):
        point = dict()
        point['pos'] = int(pos)
        label = label.upper()
        # Calculate point calibration if required
        if self.has_calibration():
            # Set to current physical position if no value supplied as argument
            if math.isinf(setpos):
                point['set'] = self.motor.position
            else:
                point['set'] = float(setpos)
            # If point exists, we use current min, max values
            if label in self.keys() and math.isinf(dmin) and math.isinf(dmax):
                p = self[label]
                min_pos = point['set'] + p['set'] - p['min']
                max_pos = point['set'] + p['set'] - p['max']
            # else, new point has new calibration,
            elif math.isinf(dmin) and math.isinf(dmax):
                min_pos = point['set']
                max_pos = point['set']
            else:
                min_pos = point['set'] + dmin
                max_pos = point['set'] + dmax

            point['min'] = min_pos
            point['max'] = max_pos

        self[label] = point
        self._update()
开发者ID:rhomspuron,项目名称:sardana,代码行数:29,代码来源:discrete.py

示例10: getBoundingBox2D

	def getBoundingBox2D(self):
		"""
		 Returns the bounding box of all active process elements in their 2D coordinate system.

		@return  :
		@author
		"""
		#Helper variables
		maxX = float("-inf")
		maxY = float("-inf")
		minX = float("inf")
		minY = float("inf")
		#Now iterate over all active process components
		for active in (self.activeProcessComponents + self.messageExchanges):
			if(hasattr(active, "hasAbstractVisualRepresentation")):
				point = active.hasAbstractVisualRepresentation.getPoint2D()
				#Max tests
				if(maxX < point[0]):
					maxX = point[0]
				if(maxY < point[1]):
					maxY = point[1]
				#Min tests
				if(minX > point[0]):
					minX = point[0]
				if(minY > point[1]):
					minY = point[1]
		#inf tests
		if(math.isinf(maxX)):
			maxX = 0
			minX = 0
		if(math.isinf(maxY)):
			maxY = 0
			minY = 0
		return [[minX, minY], [maxX, maxY]]
开发者ID:seb1b,项目名称:S-BPM_VR,代码行数:34,代码来源:Layer.py

示例11: lgamma

def lgamma(x):
    """Compute the natural logarithm of the gamma function for x."""
    if isnan(x):
        return x
    if isinf(x):
        return INFINITY
    if x == math.floor(x) and x <= 2.0:
        if x <= 0.0:
            raise ValueError("math range error")
        return 0.0
    absx = abs(x)
    if absx < 1e-20:
        return -math.log(absx)
    if x > 0.0:
        r = math.log(_lanczos_sum(x)) - _lanczos_g + (x - 0.5) * (math.log(x + _lanczos_g - 0.5) - 1)
    else:
        r = (
            math.log(math.pi)
            - math.log(abs(_sinpi(absx)))
            - math.log(absx)
            - (math.log(_lanczos_sum(absx)) - _lanczos_g + (absx - 0.5) * (math.log(absx + _lanczos_g - 0.5) - 1))
        )
    if isinf(r):
        raise OverflowError("math domain error")
    return r
开发者ID:cimarieta,项目名称:usp,代码行数:25,代码来源:rfloat.py

示例12: normalize

    def normalize(self):
        "It recovers the values got bad during the GML write-read cycle."
        if "normalized" in dir(self) and self.normalized:
            return
        if "type" in self.vs.attributes():
            virtual = self.vs.select(type=1)
            for vertex in virtual:
                for attr in ("priority", "filesize",
                             "section", "summary", "version"):
                    vertex[attr] = None
                if "architecture" in self.vs.attributes():
                    vertex["architecture"] = None
        if "revision" in self.attributes():
            revision = self["revision"]
            if isinstance(revision, float) and not math.isnan(revision):
                self["revision"] = int(revision)

        del self.vs["id"]
        integer_attributes = (
            ("type", self.vs),
            ("filesize", self.vs),
            ("type", self.es),
        )
        for attr, object_ in integer_attributes:
            if attr in object_.attributes():
                for item in object_:
                    value = item[attr]
                    if isinstance(value, float) and\
                            not math.isinf(value) and not math.isnan(value):
                        item[attr] = int(value)
                    elif value is not None and (math.isinf(value) or math.isnan(value)):
                        print("The value of the {0} attribute is {1} ({2})."
                              .format(attr, value, item["name"]))
        self.normalized = True
开发者ID:horvatha,项目名称:cxnet,代码行数:34,代码来源:debnetworki.py

示例13: dataToScreen

 def dataToScreen(self, values):
     results = []
     if not isinstance(values,list):
         values = [values]
     for value in values:
         try:
             value = float(value)
             if math.isinf(value):
                 value = 'Missing'
             elif math.isinf(value):
                 value = 'Allele Masked'
         except (ValueError,TypeError):
             if value == variant.MISSING or value == None:
                 value = 'Missing'
             elif value == variant.ALLELE_MASKED:
                 value = 'Allele Masked'
         
         if isinstance(value,str):
             index = self.cats.get(value,len(self.cats)-1)
             if index < 0:
                 results.append(self.labelTop)
             elif index > self.latticeLength:
                 results.append(self.labelBottom)
             else:
                 results.append(self.labelTop + (index+0.5)*self.cellSize)
         else:
             results.append(self.numericPixelLow + (value-self.numericDataLow)*self.dataToPixelRatio)
     return results
开发者ID:alex-r-bigelow,项目名称:compreheNGSive,代码行数:28,代码来源:parallelCoordinateWidget.py

示例14: SetNuisanceBkgValue

    def SetNuisanceBkgValue(self, nuisname, value, bkg_name, year=None):
        if self.split_bkg_by_year and year is None:
            raise Exception("ERROR: backgrounds are split by year, you must specify which year you're doing!")        
        if year not in self.years:
            raise Exception("ERROR: year {0} not in list of years!".format(year))
        if bkg_name not in self.bkg_names:
            raise Exception("ERROR: bkg {0} not in list of backgrounds!".format(bkg_name))

        fullname = self.GetFullNuisName(nuisname, year)
        fullbkg = bkg_name + (str(year) if year is not None else "")
        fullidx = self.split_bkg_names.index(fullbkg)

        if type(value)==tuple:
            if self.nuisances[fullname].type not in  ["lnN","lnU"]:
                raise Exception("ERROR: only lnN/lnU nuisances support 2-sided values!")
            if value[0]>2.05 or value[1]>2.05 or value[0]<0.3 or value[1]<0.3:
                print "WARNING: nuisance {0} has a large value {1} (year {2}). Card: {3}".format(fullname, value, year, self.name)
            if isnan(value[0]) or isinf(value[0]) or isnan(value[1]) or isinf(value[1]):
                raise Exception("ERROR: nuisance value is nan or inf for nuis {0}, background {1}, year {2}".format(nuisname, bkg_name, year))
        elif type(value)==float:
            if self.nuisances[fullname].type in ["lnN","lnU"] and (value > 2.05 or value < 0.3):
                print "WARNING: nuisance {0} has a large value {1} (year {2}). Card: {3}".format(fullname, value, year, self.name)
            if isnan(value) or isinf(value):
                raise Exception("ERROR: nuisance value is nan or inf for nuis {0}, background {1}, year {2}".format(nuisname, bkg_name, year))
        else:
            raise Exception("ERROR: value must be a float or tuple of 2 float (upper,lower) (lnN/lnU only)")

        self.nuisances[fullname].bkg_values[fullidx] = value
开发者ID:cmstas,项目名称:MT2Analysis,代码行数:28,代码来源:Datacard.py

示例15: isclose

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    '''
    Python 2 implementation of Python 3.5 math.isclose()
    https://hg.python.org/cpython/file/tip/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

    # equality check above would return false for nan, but we want
    # to return true
    if math.isnan(a) and math.isnan(b):
        return True

    # 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 * b)) or
               (diff <= math.fabs(rel_tol * a))) or
              (diff <= abs_tol))
    return result
开发者ID:theaidenlab,项目名称:straw,代码行数:34,代码来源:diff.py


注:本文中的math.isinf函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。