sys.float_info.max

Here are the examples of the python api sys.float_info.max taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

73 Examples 7

Example 1

Project: crazyflieROS
Source File: joy_driver_pid.py
View license
    def __init__(self, P=1.0, I=0.0, D=0.0):
        self.P = P
        self.I = I
        self.D = D

        self.maxP = sys.float_info.max
        self.maxI = sys.float_info.max
        self.maxD = sys.float_info.max
        self.maxTotal = sys.float_info.max

        # Useful for I part
        self.error_sum = 0.0

        # Useful for D part
        self.last_time = rospy.Time.now()
        self.last_error = 0.0# sys.float_info.max
        self.last_output = 0.0
        return

Example 2

Project: topaz
Source File: floatobject.py
View license
    @classdef.setup_class
    def setup_class(cls, space, w_cls):
        space.set_const(w_cls, "MAX", space.newfloat(sys.float_info.max))
        space.set_const(w_cls, "MIN", space.newfloat(sys.float_info.min))
        space.set_const(w_cls, "INFINITY", space.newfloat(INFINITY))
        space.set_const(w_cls, "NAN", space.newfloat(NAN))
        space.set_const(w_cls, "DIG", space.newint(sys.float_info.dig))
        space.set_const(w_cls, "EPSILON", space.newfloat(sys.float_info.epsilon))
        space.set_const(w_cls, "MANT_DIG", space.newint(sys.float_info.mant_dig))
        space.set_const(w_cls, "MAX_10_EXP", space.newint(sys.float_info.max_10_exp))
        space.set_const(w_cls, "MIN_10_EXP", space.newint(sys.float_info.min_10_exp))
        space.set_const(w_cls, "MAX_EXP", space.newint(sys.float_info.max_exp))
        space.set_const(w_cls, "MIN_EXP", space.newint(sys.float_info.min_exp))
        space.set_const(w_cls, "RADIX", space.newint(sys.float_info.radix))

Example 3

Project: Veil-Catapult
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 4

View license
def bicluster_ncut(i):
    rows, cols = cocluster.get_indices(i)
    if not (np.any(rows) and np.any(cols)):
        import sys
        return sys.float_info.max
    row_complement = np.nonzero(np.logical_not(cocluster.rows_[i]))[0]
    col_complement = np.nonzero(np.logical_not(cocluster.columns_[i]))[0]
    # Note: the following is identical to X[rows[:, np.newaxis], cols].sum() but
    # much faster in scipy <= 0.16
    weight = X[rows][:, cols].sum()
    cut = (X[row_complement][:, cols].sum() +
           X[rows][:, col_complement].sum())
    return cut / weight

Example 5

Project: BigRig
Source File: number.py
View license
    def __init__(self, interpreter):
        super(NumberConstructor, self).__init__(interpreter)
        self.prototype = interpreter.FunctionPrototype
        self.set_property('length', 1)
        self.set_property('MAX_VALUE', sys.float_info.max)
        self.set_property('MIN_VALUE', sys.float_info.min)
        self.set_property('NaN', NaN)
        self.set_property('NEGATIVE_INFINITY', -inf)
        self.set_property('POSITIVE_INFINITY', inf)

Example 6

Project: datafari
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 7

Project: iot-utilities
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 8

Project: ironpython3
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 9

Project: near-dup-detection
Source File: ndindex.py
View license
    def calculate_sketch(self, docname, doc_ngrams):
        p = self.p
        sketch = [0] * self.n
        for s in xrange(self.n):
            f_min = sys.float_info.max
            a_s = self.pairs_of_randoms[s][0]
            b_s = self.pairs_of_randoms[s][1]
            for ngram in doc_ngrams:
                fsx = (a_s*float(ngram.ID) + b_s) % p
                if fsx < f_min:
                    f_min = fsx
            sketch[s] = f_min
        return sketch

Example 10

Project: iot-utilities
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 11

Project: iot-utilities
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 12

Project: iot-utilities
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 13

Project: Roam
Source File: numberwidget.py
View license
    def _getmaxmin(self, config):
        max = config.get('max', '')
        min = config.get('min', '')
        try:
            max = float(max)
        except ValueError:
            max = sys.float_info.max

        try:
            min = float(min)
        except ValueError:
            min = -sys.float_info.min - 1

        return max, min

Example 14

Project: apilogs
Source File: core.py
View license
    def get_streams(self, log_group_name=None):
        """Returns available CloudWatch logs streams in ``log_group_name``."""
        kwargs = {'logGroupName': log_group_name or self.log_group_name}
        window_start = self.start or 0
        window_end = self.end or sys.float_info.max

        paginator = self.client.get_paginator('describe_log_streams')
        for page in paginator.paginate(**kwargs):
            for stream in page.get('logStreams', []):
                if 'firstEventTimestamp' not in stream:
                    # This is a specified log stream rather than
                    # a filter on the whole log group, so there's
                    # no firstEventTimestamp.
                    yield stream['logStreamName']
                elif max(stream['firstEventTimestamp'], window_start) <= \
                        min(stream['lastEventTimestamp'], window_end):
                    yield stream['logStreamName']

Example 15

View license
    def closestValue(self, root, target):
        """
        Divide the problem into 2 parts:
        1. find the value just smaller than target
        2. find the value just larger than target
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        lo = [-sys.float_info.max]
        self.find(root, target, lo, True)
        hi = [sys.float_info.max]
        self.find(root, target, hi, False)
        if hi[0] - target < target - lo[0]:
            return int(hi[0])
        else:
            return int(lo[0])

Example 16

Project: BigRig
Source File: number.py
View license
    def __init__(self, interpreter):
        super(NumberConstructor, self).__init__(interpreter)
        self.prototype = interpreter.FunctionPrototype
        self.set_property('length', 1)
        self.set_property('MAX_VALUE', sys.float_info.max)
        self.set_property('MIN_VALUE', sys.float_info.min)
        self.set_property('NaN', NaN)
        self.set_property('NEGATIVE_INFINITY', -inf)
        self.set_property('POSITIVE_INFINITY', inf)

Example 17

Project: scikit-fmm
Source File: pfmm.py
View license
def post_process_result(result):
    """
    post-process results from the c module (add mask)
    """
    if (result == float_info.max).any():
        mask = (result == float_info.max)
        result[mask] = 0
        result = np.ma.MaskedArray(result, mask)
    return result

Example 18

Project: NeuroM
Source File: plot_features.py
View license
def calc_limits(data, dist=None, padding=0.25):
    """Calculate a suitable range for a histogram

    Returns:
        tuple of (min, max)
    """
    dmin = sys.float_info.max if dist is None else dist.get('min',
                                                            sys.float_info.max)
    dmax = sys.float_info.min if dist is None else dist.get('max',
                                                            sys.float_info.min)
    _min = min(min(data), dmin)
    _max = max(max(data), dmax)

    padding = padding * (_max - _min)
    return _min - padding, _max + padding

Example 19

Project: stanza
Source File: summary.py
View license
def default_buckets():
    global _default_buckets
    if _default_buckets is None:
        positive_buckets = 1e-12 * 1.1 ** np.arange(0, 776.)
        positive_buckets[-1] = sys.float_info.max
        _default_buckets = np.array(list(reversed(-positive_buckets)) + [0.0] +
                                    list(positive_buckets))
    return _default_buckets

Example 20

Project: kbengine
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 21

Project: awslogs
Source File: core.py
View license
    def get_streams(self, log_group_name=None):
        """Returns available CloudWatch logs streams in ``log_group_name``."""
        kwargs = {'logGroupName': log_group_name or self.log_group_name}
        window_start = self.start or 0
        window_end = self.end or sys.float_info.max

        paginator = self.client.get_paginator('describe_log_streams')
        for page in paginator.paginate(**kwargs):
            for stream in page.get('logStreams', []):
                if 'firstEventTimestamp' not in stream:
                    # This is a specified log stream rather than
                    # a filter on the whole log group, so there's
                    # no firstEventTimestamp.
                    yield stream['logStreamName']
                elif max(stream['firstEventTimestamp'], window_start) <= \
                        min(stream['lastEventTimestamp'], window_end):
                    yield stream['logStreamName']

Example 22

Project: MeanShift_py
Source File: point_grouper.py
View license
    def _distance_to_group(self, point, group):
        min_distance = sys.float_info.max
        for pt in group:
            dist = ms_utils.euclidean_dist(point, pt)
            if dist < min_distance:
                min_distance = dist
        return min_distance

Example 23

Project: metrology
Source File: sample.py
View license
    def update(self, value, timestamp=None):
        if timestamp is None:
            timestamp = now()

        self.rescale_if_necessary()
        with self.lock:
            try:
                priority = self.weight(timestamp) / random.random()
            except (OverflowError, ZeroDivisionError):
                priority = sys.float_info.max

            if len(self.values) < self.reservoir_size:
                heapq.heappush(self.values, (priority, value))
            else:
                heapq.heappushpop(self.values, (priority, value))

Example 24

Project: kbengine
Source File: test_numbers.py
View license
    def test_float_overflow(self):
        import sys
        big_int = int(sys.float_info.max) * 2
        for t in float_types + [c_longdouble]:
            self.assertRaises(OverflowError, t, big_int)
            if (hasattr(t, "__ctype_be__")):
                self.assertRaises(OverflowError, t.__ctype_be__, big_int)
            if (hasattr(t, "__ctype_le__")):
                self.assertRaises(OverflowError, t.__ctype_le__, big_int)

Example 25

Project: awesomation
Source File: detector.py
View license
  def _probability(self, diff):
    if self._mean == 0:
      # we've only seen one heartbeat
      # so use a different formula
      # for probability
      return sys.float_info.max

    # cassandra does this, citing: /* Exponential CDF = 1 -e^-lambda*x */
    # but the paper seems to call for a probability density function
    # which I can't figure out :/
    exponent = -1.0 * diff / self._mean
    return 1 - (1.0 - math.pow(math.e, exponent))

Example 26

Project: MeanShift_py
Source File: point_grouper.py
View license
    def _distance_to_group(self, point, group):
        min_distance = sys.float_info.max
        for pt in group:
            dist = ms_utils.euclidean_dist(point, pt)
            if dist < min_distance:
                min_distance = dist
        return min_distance

Example 27

Project: metrology
Source File: sample.py
View license
    @staticmethod
    def calculate_rescale_threshold(alpha):
        # determine rescale-threshold such that we will not overflow exp() in
        # weight function, and subsequently not overflow into inf on dividing
        # by random.random()
        min_rand = 1.0 / (2 ** 32)  # minimum non-zero value from random()
        safety = 2.0                # safety pad for numerical inaccuracy
        max_value = sys.float_info.max * min_rand / safety
        return int(math.log(max_value) / alpha)

Example 28

Project: pyforms
Source File: GraphsProperties.py
View license
	def __init__(self, timelineWidget=None, parentWindow=None):
		super(GraphsProperties, self).__init__('Graphs properties', parentWindow=parentWindow)
		self.setContentsMargins(10, 10, 10, 10)
		self._timeline = timelineWidget

		# Definition of the forms fields
		self._graphs_list = ControlList('Datasets')
		self._name        = ControlText('Name')
		self._min_value   = ControlNumber('Min', 0, -sys.float_info.max, sys.float_info.max)
		self._max_value   = ControlNumber('Max', 0, -sys.float_info.max, sys.float_info.max)
		self._values_zoom = ControlSlider('Amplitude', 100, 60, 400)
		self._values_top  = ControlNumber('Bottom', 0, -1000, 1000)
		self._remove_graph_btn = ControlButton('Remove graph')
		self._value 	  = ControlLabel()

		self._formset = [
			(
				['_graphs_list','_remove_graph_btn'],
				'||', 
				[
					' ',
					'_name',
					('_min_value', '_max_value'),
					('_values_top',' '),
					'_values_zoom',
					'info:Choose one dataset and move the mouse over the graph line to visualize the coordenates.',
					'_value'
				]),
			]

		self._graphs_list.itemSelectionChanged = self.__graphs_list_selection_changed

		self._loaded = False

		self._name.changed          = self.__save_graphs_changes
		self._min_value.changed     = self.__save_graphs_changes
		self._max_value.changed     = self.__save_graphs_changes
		self._values_zoom.changed   = self.__save_graphs_changes
		self._values_top.changed    = self.__save_graphs_changes

		self._name.enabled          = False
		self._min_value.enabled     = False
		self._max_value.enabled     = False
		self._values_zoom.enabled   = False
		self._values_top.enabled    = False
		self._remove_graph_btn.enabled = False

		self._remove_graph_btn.value = self.__remove_chart

Example 29

Project: validr
Source File: validators.py
View license
@handle_default_optional_desc()
def float_validator(min=-sys.float_info.max, max=sys.float_info.max,
                    exmin=False, exmax=False):
    """Validate float string

    :param min: the min value, default -sys.float_info.max
    :param max: the max value, default sys.float_info.max
    :param exmin: exclude min value or not, default false
    :param exmax: exclude max value or not, default false
    """
    def validator(value):
        try:
            v = float(value)
        except Exception:
            raise Invalid("invalid float")
        if exmin:
            if v <= min:
                raise Invalid("value must > %d" % min)
        else:
            if v < min:
                raise Invalid("value must >= %d" % min)
        if exmax:
            if v >= max:
                raise Invalid("value must < %d" % max)
        else:
            if v > max:
                raise Invalid("value must <= %d" % max)
        return v
    return validator

Example 30

Project: TwistedBot
Source File: grid.py
View license
    def raycast_to_block(self, position, direction, max_distance=40):
        g_position = position.grid_shift()
        gx = g_position.x
        gy = g_position.y
        gz = g_position.z
        if fops.eq(0, direction.x):
            stepx = 0
            tdx = sys.float_info.max
        else:
            stepx = int(math.copysign(1, direction.x))
            tdx = abs(1 / direction.x)

        if fops.eq(0, direction.y):
            stepy = 0
            tdy = sys.float_info.max
        else:
            stepy = int(math.copysign(1, direction.y))
            tdy = abs(1 / direction.y)

        if fops.eq(0, direction.z):
            stepz = 0
            tdz = sys.float_info.max
        else:
            stepz = int(math.copysign(1, direction.z))
            tdz = abs(1 / direction.z)

        if stepx == 0:
            tmaxx = tdx
        elif stepx > 0:
            tmaxx = (math.floor(position.x) + 1 - position.x) * tdx
        else:
            tmaxx = (position.x - math.floor(position.x)) * tdx

        if stepy == 0:
            tmaxy = tdy
        elif stepy > 0:
            tmaxy = (math.floor(position.y) + 1 - position.y) * tdy
        else:
            tmaxy = (position.y - math.floor(position.y)) * tdy

        if stepz == 0:
            tmaxz = tdz
        elif stepz > 0:
            tmaxz = (math.floor(position.z) + 1 - position.z) * tdz
        else:
            tmaxz = (position.z - math.floor(position.z)) * tdz

        sqr_max_distance = max_distance * max_distance
        while True:
            if tmaxx < tmaxy:
                if tmaxx < tmaxz:
                    gx = gx + stepx
                    tmaxx = tmaxx + tdx
                else:
                    gz = gz + stepz
                    tmaxz = tmaxz + tdz

            else:
                if tmaxy < tmaxz:
                    gy = gy + stepy
                    tmaxy = tmaxy + tdy
                else:
                    gz = gz + stepz
                    tmaxz = tmaxz + tdz
            blk = self.get_block(gx, gy, gz)
            if blk.number != blocks.Air.number:
                return blk
            if (g_position.x - gx) ** 2 + (g_position.y - gy) ** 2 + (g_position.z - gz) ** 2 > sqr_max_distance:
                return blocks.Air(self, 0, 0, 0, 0)

Example 31

Project: PyEagle
Source File: alignment_tool.py
View license
    def distributePressed(self,direction):
    
        if not self.checkSelected():
            return
    
        if self.distributeModeValues.isChecked()and (self.distributeValuesHorizontalMinSpinBox.value() >= self.distributeValuesHorizontalMaxSpinBox.value() or \
                self.distributeValuesVerticalMinSpinBox.value() >= self.distributeValuesVerticalMaxSpinBox.value()):
            messageBox = QMessageBox(
            QMessageBox.Warning,"Invalid Min/Max values",
            "Minimum values must be less than maximum values for grid distribution",
            QMessageBox.Ok,self)
            messageBox.exec_()
            return

    
        unitType = self.currentGridUnitCombo.itemData(self.currentGridUnitCombo.currentIndex()).toInt()[0]

        distributeValueMode = self.DISTRIBUTE_MINMAX if self.distributeModeMinMax.isChecked() else self.DISTRIBUTE_VALUES
        
        minx=  sys.float_info.max if distributeValueMode == self.DISTRIBUTE_MINMAX else self.distributeValuesHorizontalMinSpinBox.value()
        maxx= -sys.float_info.max if distributeValueMode == self.DISTRIBUTE_MINMAX else self.distributeValuesHorizontalMaxSpinBox.value()
        miny=  sys.float_info.max if distributeValueMode == self.DISTRIBUTE_MINMAX else self.distributeValuesVerticalMinSpinBox.value()
        maxy= -sys.float_info.max if distributeValueMode == self.DISTRIBUTE_MINMAX else self.distributeValuesVerticalMaxSpinBox.value()
        spacingx = 0
        spacingy = 0
        
        itemPositions = []

        for index,selectedItem in enumerate(self.selected):
            itemx = Eaglepy.eagleToConfigured(selectedItem.x(Eaglepy.REFRESH_VALUE),unitType) if direction in [self.DIRECTION_HORIZONTAL,self.DIRECTION_GRID] else 0
            itemy = Eaglepy.eagleToConfigured(selectedItem.y(Eaglepy.REFRESH_VALUE),unitType) if direction in [self.DIRECTION_VERTICAL,  self.DIRECTION_GRID] else 0
            itemPositions.append(((itemx,itemy),index))
            if distributeValueMode == self.DISTRIBUTE_MINMAX:
                minx = itemx if itemx < minx else minx
                maxx = itemx if itemx > maxx else maxx
                miny = itemy if itemy < miny else miny
                maxy = itemy if itemy > maxy else maxy
        

                
        if direction in [self.DIRECTION_HORIZONTAL,self.DIRECTION_VERTICAL]:
            if direction == self.DIRECTION_HORIZONTAL:
                spacingx = abs((float(maxx) - float(minx)) / (len(self.selected)-1)) if self.DIRECTION_HORIZONTAL else 0
                sortedSelected = sorted(self.selected,key=lambda selected:selected.x())
            elif direction == self.DIRECTION_VERTICAL:
                spacingy = abs((float(maxy) - float(miny)) / (len(self.selected)-1)) if self.DIRECTION_VERTICAL   else 0
                sortedSelected = sorted(self.selected,key=lambda selected:selected.y())
                
            script = ""
            currentspacingx = 0
            currentspacingy = 0
            
            for selectedItem in sortedSelected:
                
                itemx = Eaglepy.eagleToConfigured(selectedItem.x(Eaglepy.REFRESH_VALUE),unitType)
                itemy = Eaglepy.eagleToConfigured(selectedItem.y(Eaglepy.REFRESH_VALUE),unitType)
                
                if direction == self.DIRECTION_HORIZONTAL: 
                    script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (minx+currentspacingx,itemy))
                    selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(minx+currentspacingx,unitType)
                    selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemy ,unitType)
                elif direction == self.DIRECTION_VERTICAL:
                    script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (itemx,miny+currentspacingy))
                    selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemx,unitType)
                    selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(miny+currentspacingy ,unitType)
                    
                currentspacingx += spacingx
                currentspacingy += spacingy
                    
                
        elif direction == self.DIRECTION_GRID:
            
            rows = self.distributeGridRowsSpinBox.value()
            columns = self.distributeGridColsSpinBox.value()
            
            
            spacingx = abs((float(maxx) - float(minx)) / (rows-1))
            spacingy = abs((float(maxy) - float(miny)) / (columns-1))
            
            if rows*columns < len(self.selected):
                messageBox = QMessageBox(
                QMessageBox.Warning,"Too many items selected",
                "%d items exceeds the maximum for the current grid size.\nFor %d rows * %d columns the maximum number of selected items is %d" % (len(self.selected),rows,columns,rows*columns),
                QMessageBox.Ok,self)
                
                return messageBox.exec_()
            
            distance = lambda p1,p2: abs(math.sqrt(math.pow(p2[0]-p1[0],2) + math.pow(p2[1]-p1[1],2)))
            script = ""    
            

            complete = False
            for rowIndex in range(rows):
                for colIndex in range(columns):
                    if (rowIndex*columns)+colIndex == len(self.selected):
                        complete = True 
                        break
                
                    newx = minx+rowIndex*spacingx
                    newy = miny+colIndex*spacingy

                    closestItem = min(itemPositions,key=lambda item:distance(item[0],(newx,newy)))
                    itemPositions.remove(closestItem)
                    script += ("MOVE %s" % self.selected[closestItem[1]].name()) + (" (%f %f);" % (newx,newy))
                    self.selected[closestItem[1]].x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(newx, unitType)
                    self.selected[closestItem[1]].y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(newy ,unitType)
                    
                if complete:
                    break

        

        Eaglepy.executescr(script)

Example 32

Project: TwistedBot
Source File: grid.py
View license
    def raycast_to_block(self, position, direction, max_distance=40):
        g_position = position.grid_shift()
        gx = g_position.x
        gy = g_position.y
        gz = g_position.z
        if fops.eq(0, direction.x):
            stepx = 0
            tdx = sys.float_info.max
        else:
            stepx = int(math.copysign(1, direction.x))
            tdx = abs(1 / direction.x)

        if fops.eq(0, direction.y):
            stepy = 0
            tdy = sys.float_info.max
        else:
            stepy = int(math.copysign(1, direction.y))
            tdy = abs(1 / direction.y)

        if fops.eq(0, direction.z):
            stepz = 0
            tdz = sys.float_info.max
        else:
            stepz = int(math.copysign(1, direction.z))
            tdz = abs(1 / direction.z)

        if stepx == 0:
            tmaxx = tdx
        elif stepx > 0:
            tmaxx = (math.floor(position.x) + 1 - position.x) * tdx
        else:
            tmaxx = (position.x - math.floor(position.x)) * tdx

        if stepy == 0:
            tmaxy = tdy
        elif stepy > 0:
            tmaxy = (math.floor(position.y) + 1 - position.y) * tdy
        else:
            tmaxy = (position.y - math.floor(position.y)) * tdy

        if stepz == 0:
            tmaxz = tdz
        elif stepz > 0:
            tmaxz = (math.floor(position.z) + 1 - position.z) * tdz
        else:
            tmaxz = (position.z - math.floor(position.z)) * tdz

        sqr_max_distance = max_distance * max_distance
        while True:
            if tmaxx < tmaxy:
                if tmaxx < tmaxz:
                    gx = gx + stepx
                    tmaxx = tmaxx + tdx
                else:
                    gz = gz + stepz
                    tmaxz = tmaxz + tdz

            else:
                if tmaxy < tmaxz:
                    gy = gy + stepy
                    tmaxy = tmaxy + tdy
                else:
                    gz = gz + stepz
                    tmaxz = tmaxz + tdz
            blk = self.get_block(gx, gy, gz)
            if blk.number != blocks.Air.number:
                return blk
            if (g_position.x - gx) ** 2 + (g_position.y - gy) ** 2 + (g_position.z - gz) ** 2 > sqr_max_distance:
                return blocks.Air(self, 0, 0, 0, 0)

Example 33

Project: PyEagle
Source File: alignment_tool.py
View license
    def alignPressed(self,direction):
        unitType = self.currentGridUnitCombo.itemData(self.currentGridUnitCombo.currentIndex()).toInt()[0]
        
        minx=sys.float_info.max
        maxx=-sys.float_info.max
        miny=sys.float_info.max
        maxy=-sys.float_info.max

        for selectedItem in self.selected:
            itemx = Eaglepy.eagleToConfigured(selectedItem.x(Eaglepy.REFRESH_VALUE),unitType) if direction in [self.DIRECTION_LEFT,self.DIRECTION_RIGHT,self.DIRECTION_CENTER_V] else 0
            itemy = Eaglepy.eagleToConfigured(selectedItem.y(Eaglepy.REFRESH_VALUE),unitType) if direction in [self.DIRECTION_TOP,self.DIRECTION_BOTTOM,self.DIRECTION_CENTER_H] else 0
            
            minx = itemx if itemx < minx else minx
            maxx = itemx if itemx > maxx else maxx
            miny = itemy if itemy < miny else miny
            maxy = itemy if itemy > maxy else maxy
        
        centerx = minx + ((maxx - minx)/2)
        centery = miny + ((maxy - miny)/2)
        
        script = ""
        for selectedItem in self.selected:
            itemx = Eaglepy.eagleToConfigured(selectedItem.x(Eaglepy.REFRESH_VALUE),unitType)
            itemy = Eaglepy.eagleToConfigured(selectedItem.y(Eaglepy.REFRESH_VALUE),unitType)
            
            if direction == self.DIRECTION_LEFT: 
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (minx,itemy))
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(minx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemy ,unitType)
            elif direction == self.DIRECTION_RIGHT:
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (maxx,itemy))
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(maxx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemy ,unitType)
            elif direction == self.DIRECTION_CENTER_V:
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (centerx,itemy))
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(centerx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemy ,unitType)
            elif direction == self.DIRECTION_TOP:
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (itemx,maxy))  
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(maxy ,unitType)
            elif direction == self.DIRECTION_BOTTOM:
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (itemx,miny))
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(miny ,unitType)
            elif direction == self.DIRECTION_CENTER_H:
                script += ("MOVE %s" % selectedItem.name()) + (" (%f %f);" % (itemx,centery))
                selectedItem.x.__dict__["cachedValue"] = Eaglepy.configuredToEagle(itemx,unitType)
                selectedItem.y.__dict__["cachedValue"] = Eaglepy.configuredToEagle(centery ,unitType)
                
        Eaglepy.executescr(script)

Example 34

Project: topaz
Source File: test_floatobject.py
View license
    def test_max(self, space):
        assert space.float_w(space.execute("return Float::MAX")) == sys.float_info.max

Example 35

View license
def run_gradient_descent_search(X, y, lossfunc, max_nsteps, learning_rate,
                                verbose=False):
    """Helper function to run GD search for the given data and loss function.

    For help on arguments, see the gradient_descent function. max_nsteps is like
    nsteps except that this function will stop once the loss isn't changing much
    any more, which may take fewer than max_nsteps steps.
    """
    n = X.shape[1]
    gradient_descent_iter = gradient_descent(X, y,
                                             init_theta=np.random.randn(n, 1),
                                             lossfunc=lossfunc,
                                             nsteps=max_nsteps,
                                             learning_rate=learning_rate)
    # Run GD until the changes in loss converge to some small value, or until
    # max_nstepsis reached.
    prev_loss = sys.float_info.max
    converge_step = 0
    for i, (theta, loss) in enumerate(gradient_descent_iter):
        if verbose:
            print(i, ':', loss)
        # Convergence of loss beneath a small threshold: this threshold can also
        # be made configurable, if needed.
        if abs(loss - prev_loss) < 1e-5:
            converge_step = i
            break
        prev_loss = loss
    print('... loss converged at step {0}'.format(converge_step))
    return theta

Example 36

Project: datafari
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        self.assertEqual(float(halfway-1), DBL_MAX)
        self.assertRaises(OverflowError, float, halfway)
        self.assertEqual(float(1-halfway), -DBL_MAX)
        self.assertRaises(OverflowError, float, -halfway)
        self.assertRaises(OverflowError, float, top_power-1)
        self.assertRaises(OverflowError, float, top_power)
        self.assertRaises(OverflowError, float, top_power+1)
        self.assertRaises(OverflowError, float, 2*top_power-1)
        self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)

Example 37

Project: pymo
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        self.assertEqual(float(halfway-1), DBL_MAX)
        self.assertRaises(OverflowError, float, halfway)
        self.assertEqual(float(1-halfway), -DBL_MAX)
        self.assertRaises(OverflowError, float, -halfway)
        self.assertRaises(OverflowError, float, top_power-1)
        self.assertRaises(OverflowError, float, top_power)
        self.assertRaises(OverflowError, float, top_power+1)
        self.assertRaises(OverflowError, float, 2*top_power-1)
        self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)

Example 38

Project: cmonkey2
Source File: membership.py
View license
def adjust_cluster(membership, cluster, rowscores, cutoff, limit):
    """adjust a single cluster"""
    def max_row_in_column(matrix, column):
        """returns a pair of the maximum row index and score in the given matrix and column"""
        sm = matrix.submatrix_by_name(wh, [matrix.column_names[column]])
        sm_values = sm.values
        max_row = 0
        max_score = -sys.float_info.max
        for row in range(sm.num_rows):
            if sm_values[row][0] > max_score:
                max_score = sm_values[row, 0]
                max_row = row
        return sm.row_names[max_row]

    old_rows = membership.rows_for_cluster(cluster)
    not_in = [(i, row) for i, row in enumerate(rowscores.row_names)
              if row not in old_rows]
    threshold = rowscores.submatrix_by_name(old_rows,
                                            [rowscores.column_names[cluster - 1]]).quantile(cutoff)
    wh = []
    rs_values = rowscores.values
    for row, row_name in not_in:
        if rs_values[row, cluster - 1] < threshold:
            wh.append(row_name)
    if len(wh) == 0 or len(wh) > limit:
        return {}  # return unmodified row membership

    tries = 0
    result = {}
    while len(wh) > 0 and tries < MAX_ADJUST_TRIES:
        wh2 = max_row_in_column(rowscores, cluster - 1)
        result[wh2] = cluster
        wh.remove(wh2)
        tries += 1
    old_num = len(membership.rows_for_cluster(cluster))
    logging.debug("CLUSTER %d, # ROWS BEFORE: %d, AFTER: %d",
                  cluster, old_num, old_num + len(result))
    return result

Example 39

Project: citest
Source File: base_agent.py
View license
  def __wait_helper(self, poll_every_secs, max_secs, trace):
    """Helper function for wait to keep its try/finally block simple.

    Args:
      poll_every_secs: [float] Frequency to poll.
      max_secs: [float] How long to poll before giving up. None is indefinite.
      trace_every: [bool] Whether to log each attempt.
    """
    logger = logging.getLogger(__name__)
    now = self._now()
    end_time = sys.float_info.max if max_secs is None else now + max_secs
    next_log_secs = now + 60
    while not self.finished:
        # pylint: disable=bad-indentation
        now = self._now()
        secs_remaining = end_time - now
        if secs_remaining <= 0:
          logger.debug('Timed out')
          return False

        sleep_secs = (poll_every_secs if max_secs is None
                      else min(secs_remaining, poll_every_secs))

        # Write something into the log file to indicate we are still here.
        if now >= next_log_secs:
          if max_secs is None:
            logger.debug(
                'Still waiting (no timeout). Check in %r secs', sleep_secs)
          else:
            logger.debug(
                'Still waiting (approx %d left). Check in %r secs',
                secs_remaining, sleep_secs)
          # Hardcoded once-a-minute confirmation that we're still waiting.
          next_log_secs = now + 60

        self._do_sleep(sleep_secs)
        self.refresh(trace=trace)

    return True

Example 40

Project: billing-export-python
Source File: main.py
View license
    def isAlertTriggered(self, project, current_date):
        """Return true if an alert should trigger."""

        # See if the project matches.
        if self.project is not None and self.project != project:
            return False

        # billing data for the current date.
        current_dtd = GetDataTableData(project, current_date)
        current_target_value = current_dtd.GetTargetAmount(self.target_value)
        logging.debug('\ncurrent_dtd.rows=' + repr(current_dtd.rows) +
                      '\ncurrent_dtd.columns=' + repr(current_dtd.columns) +
                      '\ncurrent_target_value=' + repr(current_target_value))
        # if the alert trigger is based on a past billing data,
        # lookup the past billing data.
        resulting_target_value = current_target_value
        if self.trigger != AlertTrigger.TOTAL_AMOUNT:
            elapsed_range = timedelta(-self.range.number)
            past_date = current_date + elapsed_range
            past_dtd = GetDataTableData(project, past_date)
            past_target_value = past_dtd.GetTargetAmount(self.target_value)
            # calculate the difference between the past and current billing
            # data.
            if self.trigger == AlertTrigger.TOTAL_CHANGE:
                resulting_target_value = current_target_value - \
                    past_target_value
            else:  # must be RELATIVE_CHANGE
                if past_target_value == 0:
                    resulting_target_value = sys.float_info.max
                else:
                    resulting_target_value = (
                        (current_target_value - past_target_value) /
                        past_target_value) * 100
            logging.debug('relative_change or total_change alert :\n' +
                          repr(self) + '\ncurrent_target_value=' +
                          str(current_target_value) +
                          '\npast_target_value=' + str(past_target_value) +
                          '\npast_dtd.rows=' + repr(past_dtd.rows) +
                          '\npast_dtd.columns=' + repr(past_dtd.columns))
        is_triggered = False

        # is the difference/total over the alert's threshold?
        if self.trigger_value < 0:
            if resulting_target_value < self.trigger_value:
                is_triggered = True
        else:
            if resulting_target_value > self.trigger_value:
                is_triggered = True
        logging.debug('Evaluating ' + repr(self) + ' resulting_target_value='
                      + repr(resulting_target_value) + ' and is_triggered=' +
                      str(is_triggered))
        return is_triggered

Example 41

Project: deepy
Source File: server.py
View license
    def __init__(self, port=CONTROLLER_PORT, easgd_alpha=0.5,
                 # Following arguments can be received from workers
                 start_halving_at=6, end_at=10, step_len=10,
                 valid_freq=1500, learning_rate=0.1, log_path=None):
        """
        Initialize the controller.

        Args:
            port (int): batches in one training step
            easgd_alpha (float)
        """

        Controller.__init__(self, port)
        self.epoch_start_halving = start_halving_at
        self.end_at = end_at
        self.step_len = step_len
        self.start_time = None
        self.rand = np.random.RandomState(3)
        self.epoch = 0
        self._current_iter = 0
        self._iters_from_last_valid = 0
        self._evaluating = False
        self._valid_freq = valid_freq
        self._done = False
        self._lr = learning_rate
        self._easgd_alpha = easgd_alpha
        self._training_names = []
        self._evaluation_names = []
        self._best_valid_cost = sys.float_info.max
        self._lock = Lock()

        self.num_train_batches = 0
        self.batch_pool = []
        self._train_costs = []
        self._epoch_start_time = None
        self.prepared_worker_pool = set()
        self.log_file = open(log_path, "w") if log_path else None
        if log_path:
            logging.info("write logs into {}".format(log_path))
        logging.info("multi-gpu server is listening port {}".format(port))

Example 42

Project: openwrt-mt7620
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        self.assertEqual(float(halfway-1), DBL_MAX)
        self.assertRaises(OverflowError, float, halfway)
        self.assertEqual(float(1-halfway), -DBL_MAX)
        self.assertRaises(OverflowError, float, -halfway)
        self.assertRaises(OverflowError, float, top_power-1)
        self.assertRaises(OverflowError, float, top_power)
        self.assertRaises(OverflowError, float, top_power+1)
        self.assertRaises(OverflowError, float, 2*top_power-1)
        self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)

Example 43

View license
def tangentRatioAt(cubic, T):
	debug = (cubic[0].x == debug_X)
	(l0, l1, l2, l3), (r3, r2, r1, r0) = splitCubic(T, cubic)
	u = det2x2(l1-l0, l2-l3)
	if abs(u) < eps:
		a = l0
	else:
		t = - det2x2(l0-l2, l2-l3) / u
		a = l0 + ( t * (l1-l0) )
	left_len = (a-l3).length()
	u = det2x2(r1-r0, r2-r3)
	if abs(u) < eps:
		b = r0
	else:
		v = det2x2(r0-r2, r2-r3)
		t = - v / u
		b = r0 + ( t * (r1-r0) )
	right_len = (b-r3).length()
	retval = (sys.float_info.max, T, a, b)
	if T < 1.0:
		if right_len > eps:
			retval = (left_len / right_len - 1.0, T, a, b)
	if debug:
		print "ratio", retval[0], "at", retval[1]
	return retval

Example 44

Project: openwrt-mt7620
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        self.assertEqual(float(halfway-1), DBL_MAX)
        self.assertRaises(OverflowError, float, halfway)
        self.assertEqual(float(1-halfway), -DBL_MAX)
        self.assertRaises(OverflowError, float, -halfway)
        self.assertRaises(OverflowError, float, top_power-1)
        self.assertRaises(OverflowError, float, top_power)
        self.assertRaises(OverflowError, float, top_power+1)
        self.assertRaises(OverflowError, float, 2*top_power-1)
        self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)

Example 45

Project: cupy
Source File: test_ranges.py
View license
    @testing.numpy_cupy_allclose()
    def test_linspace_float_overflow(self, xp):
        return xp.linspace(0., sys.float_info.max / 5, 10, dtype=float)

Example 46

Project: imagrium
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        #XXX: Most or all of these fail on Jython ATM - needs investigation.
        if not test_support.is_jython:
            self.assertEqual(float(halfway-1), DBL_MAX)
            self.assertRaises(OverflowError, float, halfway)
            self.assertEqual(float(1-halfway), -DBL_MAX)
            self.assertRaises(OverflowError, float, -halfway)
            self.assertRaises(OverflowError, float, top_power-1)
            self.assertRaises(OverflowError, float, top_power)
            self.assertRaises(OverflowError, float, top_power+1)
            self.assertRaises(OverflowError, float, 2*top_power-1)
            self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)

Example 47

View license
    def _traverse_grid_(self):
        """ Solve using linear systems of equations """
        aux = np.zeros(self.M-1)
        new_values = np.zeros(self.M-1)

        for j in reversed(range(self.N)):
            aux[0] = self.alpha[1]*(self.boundary_values[j] +
                                    self.boundary_values[j+1])
            rhs = np.dot(self.M2, self.past_values) + aux
            old_values = np.copy(self.past_values)
            error = sys.float_info.max

            while self.tol < error:
                new_values[0] = \
                    max(self.payoffs[0],
                        old_values[0] +
                        self.omega/(1-self.beta[1]) *
                        (rhs[0] -
                         (1-self.beta[1])*old_values[0] +
                         (self.gamma[1]*old_values[1])))

                for k in range(self.M-2)[1:]:
                    new_values[k] = \
                        max(self.payoffs[k],
                            old_values[k] +
                            self.omega/(1-self.beta[k+1]) *
                            (rhs[k] +
                             self.alpha[k+1]*new_values[k-1] -
                             (1-self.beta[k+1])*old_values[k] +
                             self.gamma[k+1]*old_values[k+1]))

                new_values[-1] = \
                    max(self.payoffs[-1],
                        old_values[-1] +
                        self.omega/(1-self.beta[-2]) *
                        (rhs[-1] +
                         self.alpha[-2]*new_values[-2] -
                         (1-self.beta[-2])*old_values[-1]))

                error = np.linalg.norm(new_values - old_values)
                old_values = np.copy(new_values)

            self.past_values = np.copy(new_values)

        self.values = np.concatenate(([self.boundary_values[0]],
                                      new_values,
                                      [0]))

Example 48

Project: DensityPeakCluster
Source File: cluster.py
View license
def load_paperdata(distance_f):
	'''
	Load distance from data

	Args:
		distance_f : distance file, the format is column1-index 1, column2-index 2, column3-distance
	
	Returns:
	    distances dict, max distance, min distance, max continues id
	'''
	logger.info("PROGRESS: load data")
	distances = {}
	min_dis, max_dis = sys.float_info.max, 0.0
	max_id = 0
	with open(distance_f, 'r') as fp:
		for line in fp:
			x1, x2, d = line.strip().split(' ')
			x1, x2 = int(x1), int(x2)
			max_id = max(max_id, x1, x2)
			dis = float(d)
			min_dis, max_dis = min(min_dis, dis), max(max_dis, dis)
			distances[(x1, x2)] = float(d)
			distances[(x2, x1)] = float(d)
	for i in xrange(max_id):
		distances[(i, i)] = 0.0
	logger.info("PROGRESS: load end")
	return distances, max_dis, min_dis, max_id

Example 49

View license
    def train(self,
            training_data,
            maxiter=5000,
            alpha=0.5,
            epsilon=1.5e-8,
            display_progress=True):       
        iteration = 0
        error = sys.float_info.max
        while error > epsilon and iteration < maxiter:            
            error = 0.0
            shuffle(training_data)
            for ex, labels in training_data:
                self.forward_propagation(ex)
                error += self.backward_propagation(labels, alpha=alpha)           
            if display_progress:
                sys.stderr.write('\r')
                sys.stderr.write('Error at iteration {}: {}'.format(iteration, error))
                sys.stderr.flush()                
            iteration += 1
        if display_progress:
            sys.stderr.write('\n')

Example 50

Project: chipsec
Source File: test_long.py
View license
    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
                         "test requires IEEE 754 doubles")
    def test_float_conversion(self):
        import sys
        DBL_MAX = sys.float_info.max
        DBL_MAX_EXP = sys.float_info.max_exp
        DBL_MANT_DIG = sys.float_info.mant_dig

        exact_values = [0L, 1L, 2L,
                         long(2**53-3),
                         long(2**53-2),
                         long(2**53-1),
                         long(2**53),
                         long(2**53+2),
                         long(2**54-4),
                         long(2**54-2),
                         long(2**54),
                         long(2**54+4)]
        for x in exact_values:
            self.assertEqual(long(float(x)), x)
            self.assertEqual(long(float(-x)), -x)

        # test round-half-even
        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))

        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
                     (13, 12), (14, 16), (15, 16)]:
            for p in xrange(15):
                self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))

        # behaviour near extremes of floating-point range
        long_dbl_max = long(DBL_MAX)
        top_power = 2**DBL_MAX_EXP
        halfway = (long_dbl_max + top_power)//2
        self.assertEqual(float(long_dbl_max), DBL_MAX)
        self.assertEqual(float(long_dbl_max+1), DBL_MAX)
        self.assertEqual(float(halfway-1), DBL_MAX)
        self.assertRaises(OverflowError, float, halfway)
        self.assertEqual(float(1-halfway), -DBL_MAX)
        self.assertRaises(OverflowError, float, -halfway)
        self.assertRaises(OverflowError, float, top_power-1)
        self.assertRaises(OverflowError, float, top_power)
        self.assertRaises(OverflowError, float, top_power+1)
        self.assertRaises(OverflowError, float, 2*top_power-1)
        self.assertRaises(OverflowError, float, 2*top_power)
        self.assertRaises(OverflowError, float, top_power*top_power)

        for p in xrange(100):
            x = long(2**p * (2**53 + 1) + 1)
            y = long(2**p * (2**53+ 2))
            self.assertEqual(long(float(x)), y)

            x = long(2**p * (2**53 + 1))
            y = long(2**p * 2**53)
            self.assertEqual(long(float(x)), y)