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


Python math.floor函数代码示例

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


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

示例1: calculate_median

 def calculate_median(self,
                      minutes=1):
     """
     Calculates the median of all values in the collection
     after (now - minutes)
     """
     now = utc_now()
     created_after = now - timedelta(minutes=1)
     queryset = self.filter_query(created_after=created_after)
     count = queryset.count()
     # If there is no value within past 1 minute return None
     if count == 0:
         return None
     # Pick the center element in the collection
     # if the collection has a count which is odd
     elif (count % 2) != 0:
         return queryset.skip(math.floor(count/2))\
             .limit(1)\
             .all()[0].value
     # Pick the center 2 elements in the collection and calculate the avg
     # if the collection has a count which is even
     elif (count % 2) == 0:
         center_elements = queryset.skip(math.floor(count/2) - 1)\
             .limit(2)\
             .all()
         median = (center_elements[0].value + center_elements[1].value)/2.0
         return median
开发者ID:joeljames,项目名称:median-service,代码行数:27,代码来源:repositories.py

示例2: render2

	def render2(a, b, vol, pos, knum, endamp = .25, sm = 10):
	    b2 = (1. - pause) * b
	    l=waves2(a, b2)
	    ow=""
	    q=int(l[0]*l[1])

	    lf = log(a)
	    t = (lf-3.) / (8.5-3.)
	    volfac = 1. + .8 * t * cos(pi/5.3*(lf-3.))
	    snd_len = int((10.-lf)*q)
	    if lf < 4: snd_len *= 2
	    x = np.arange(snd_len)
	    s = x / float(q)

	    ls = np.log(1. + s)
	    kp_len = int(l[0])
	    kps1 = np.zeros(snd_len)
	    kps2 = np.zeros(snd_len)
	    kps1[:kp_len] = np.random.normal(size = kp_len)

	    for t in range(kp_len):
		kps2[t] = kps1[t:t+sm].mean()
	    delt = float(l[0])
	    li = int(floor(delt))
	    hi = int(ceil(delt))
	    ifac = delt % 1
	    delt2 = delt * (floor(delt) - 1) / floor(delt)
	    ifac2 = delt2 % 1
	    falloff = (4./lf*endamp)**(1./l[1])
	    for t in range(hi, snd_len):
		v1 = ifac * kps2[t-hi]   + (1.-ifac) * kps2[t-li]
		v2 = ifac2 * kps2[t-hi+1] + (1.-ifac2) * kps2[t-li+1]
	        kps2[t] += .5 * (v1 + v2) * falloff
	    data[pos:pos+snd_len] += kps2*vol*volfac
开发者ID:Allie-Podnar,项目名称:test-project,代码行数:34,代码来源:pysynth_s.py

示例3: segment_units

	def segment_units(self, sfid, verb=False):
		"""
		This function takes the list of unit breakpoints, plus the raw metadata, and assembles 'cooked' segments in the corpus segtable.
		
		Note: currently ignores the amplitude scalars (aside from generating stats)...
		
		"""
		segmented = self.get_sorted_units_list(sfid)
		raw_amps, raw_mfccs, raw_chromas = self.get_raw_metadata(sfid) # , raw_chromas
		amps, reheated = [], []
		
		if verb: print 'raw: ', raw_amps
		amps_stripped = np.nan_to_num(raw_amps)
		if verb: print 'amps_stripped: ', amps_stripped
		mfccs_stripped = np.nan_to_num(raw_mfccs)
		if verb: print 'mfccs_stripped: ', mfccs_stripped
		chromas_stripped = np.nan_to_num(raw_chromas)
		if verb: print 'chromas_stripped: ', chromas_stripped

		for relid, sfu in enumerate(segmented):

			offset = int(math.floor(sfu.onset / self.HOP_SECS))
			dur = int(math.floor(sfu.dur / self.HOP_SECS))
			if verb: print '[[', offset, '|', dur, ']]'
			self.sftree.nodes[sfid].add_metadata_for_relid(relid, powers=self.feat.powers.proc_funcs[0](amps_stripped, offset, dur))
			# WHY ARE THE FUNCTION SIGNATURES DIFFERENT FOR OFFSET AND DUR???
			self.sftree.nodes[sfid].add_metadata_for_relid(relid, mfccs=self.feat.proc_funcs[0](mfccs_stripped[offset:(offset+dur)]))
			if verb: print self.feat.proc_funcs[1]
			if verb: print mfccs_stripped[offset:(offset+dur)]
			self.sftree.nodes[sfid].add_metadata_for_relid(relid, mfcc_vars=self.feat.proc_funcs[1](mfccs_stripped[offset:(offset+dur)]))
			self.sftree.nodes[sfid].add_metadata_for_relid(relid, chromas=self.feat.proc_funcs[0](chromas_stripped[offset:(offset+dur)]))
			self.sftree.nodes[sfid].add_metadata_for_relid(relid, chroma_vars=self.feat.proc_funcs[1](chromas_stripped[offset:(offset+dur)]))
开发者ID:kitefishlabs,项目名称:CorpusDB,代码行数:32,代码来源:corpusdb.py

示例4: format

 def format(self, record):
     '''format a record for display'''
     returns = []
     line_len = self.width
     if type(record.msg) in types.StringTypes:
         for line in logging.Formatter.format(self, record).split('\n'):
             if len(line) <= line_len:
                 returns.append(line)
             else:
                 inner_lines = int(math.floor(float(len(line)) / line_len))+1
                 for i in xrange(inner_lines):
                     returns.append("%s" % (line[i*line_len:(i+1)*line_len]))
     elif type(record.msg) == types.ListType:
         if not record.msg:
             return ''
         # getMessage() must be called so that arguments are substituted; eval() is used to turn the string back into a list
         msgdata = eval(record.getMessage())
         msgdata.sort()
         msgwidth = self.width
         columnWidth = max([len(str(item)) for item in msgdata])
         columns = int(math.floor(float(msgwidth) / (columnWidth+2)))
         lines = int(math.ceil(float(len(msgdata)) / columns))
         for lineNumber in xrange(lines):
             indices = [idx for idx in [(colNum * lines) + lineNumber
                                        for colNum in range(columns)] if idx < len(msgdata)]
             format = (len(indices) * (" %%-%ds " % columnWidth))
             returns.append(format % tuple([msgdata[idx] for idx in indices]))
     #elif type(record.msg) == lxml.etree._Element:
     #    returns.append(str(xml_print(record.msg)))
     else:
         returns.append(str(record.getMessage()))
     if record.exc_info:
         returns.append(self.formatException(record.exc_info))
     return '\n'.join(returns)
开发者ID:benmcclelland,项目名称:cobalt,代码行数:34,代码来源:Logging.py

示例5: findMousePos

    def findMousePos(self, pos):
        # put hit position in window relative coords
        x = pos[0] - self.rect[0] - 2
        y = pos[1] - self.rect[1] - 5
        
        font_width, font_heigth = getRenderer().getTextSize( ' ', self.font )
        
        col = max( math.floor( (float(x) / float(font_width)) ) + self.scroll[0], 0 )
        row = max( math.floor( (float(y) / float(font_heigth)) ) + self.scroll[1], 0 )
        
        r, c, i = 0, 0, 0
        while r != row:
            try: i = self.text.index( '\n', i ) + 1
            except: break
            r += 1
        
        while c < col:
            if i >= len( self.text) or self.text[i] == '\n':
                break
            elif self.text[i] == '\t':
                if ( c + 4 > col ): break
                c += 8
            else:
                c += 1
            i += 1

        return min( max( i, 0 ), len( self.text ) )
开发者ID:bcamellia,项目名称:PySBD,代码行数:27,代码来源:entry.py

示例6: SetValue

    def SetValue(self, value):
        """ Sets the FloatSpin value. """

        if not self._textctrl or not self.InRange(value):
            return

        if self._snapticks and self._increment != 0.0:

            finite, snap_value = self.IsFinite(value)

            if not finite: # FIXME What To Do About A Failure?

                if (snap_value - floor(snap_value) < ceil(snap_value) - snap_value):
                    value = self._defaultvalue + floor(snap_value)*self._increment
                else:
                    value = self._defaultvalue + ceil(snap_value)*self._increment

        strs = ("%100." + str(self._digits) + self._textformat[1])%value
        strs = strs.strip()
        strs = self.ReplaceDoubleZero(strs)

        if value != self._value or strs != self._textctrl.GetValue():

            self._textctrl.SetValue(strs)
            self._textctrl.DiscardEdits()
            self._value = value
开发者ID:AceZOfZSpades,项目名称:RankPanda,代码行数:26,代码来源:floatspin.py

示例7: plotLimits

    def plotLimits(self, xy):
        ymax = -1.e10
        ymin = 1.e10
        for x, y in xy:
            if y > ymax: ymax = y
            if y < ymin: ymin = y

        dy = abs(ymax - ymin)
        if dy < 0.2*ymin:
            ymin = ymin*.9
            ymax = ymax*1.1
            dy = abs(ymax - ymin)
        else:
            ymin = ymin - 0.1*dy
            ymax = ymax + 0.1*dy
            dy = abs(ymax - ymin)

        p10 = math.floor(math.log10(0.1*dy))
        fctr = math.pow(10.0, p10)
        mm = [2.0, 2.5, 2.0]
        i = 0
        while dy/fctr > 5:
            fctr = mm[i % 3]*fctr
            i = i + 1
        ymin = fctr*math.floor(ymin/fctr)
        ymax = fctr*(math.floor(ymax/fctr + 1))
        return (ymin, ymax, fctr)
开发者ID:Cantera,项目名称:cantera-svn,代码行数:27,代码来源:SpeciesInfo.py

示例8: tile

def tile(lng, lat, zoom, truncate=False):
    """Get the tile containing a longitude and latitude

    Parameters
    ----------
    lng, lat : float
        A longitude and latitude pair in decimal degrees.
    zoom : int
        The web mercator zoom level.
    truncate : bool, optional
        Whether or not to truncate inputs to limits of web mercator.

    Returns
    -------
    Tile
    """
    if truncate:
        lng, lat = truncate_lnglat(lng, lat)
    lat = math.radians(lat)
    n = 2.0 ** zoom
    xtile = int(math.floor((lng + 180.0) / 360.0 * n))

    try:
        ytile = int(math.floor((1.0 - math.log(
            math.tan(lat) + (1.0 / math.cos(lat))) / math.pi) / 2.0 * n))
    except ValueError:
        raise InvalidLatitudeError(
            "Y can not be computed for latitude {} radians".format(lat))
    else:
        return Tile(xtile, ytile, zoom)
开发者ID:mapbox,项目名称:mercantile,代码行数:30,代码来源:__init__.py

示例9: optimize_for_oom

 def optimize_for_oom(oom):
     self.colorbar_step = math.floor(step / 10**oom)*10**oom
     self.colorbar_vmin = math.floor(vmin / 10**oom)*10**oom
     self.colorbar_vmax = self.colorbar_vmin + \
     self.colorbar_step * (number_of_ticks - 1)
     self.colorbar_locs = np.arange(0, number_of_ticks
                 )* self.colorbar_step + self.colorbar_vmin
开发者ID:AEljarrat,项目名称:hyperspy,代码行数:7,代码来源:image.py

示例10: _write_float

def _write_float(f, x):
	import math
	if x < 0:
		sign = 0x8000
		x = x * -1
	else:
		sign = 0
	if x == 0:
		expon = 0
		himant = 0
		lomant = 0
	else:
		fmant, expon = math.frexp(x)
		if expon > 16384 or fmant >= 1:		# Infinity or NaN
			expon = sign|0x7FFF
			himant = 0
			lomant = 0
		else:					# Finite
			expon = expon + 16382
			if expon < 0:			# denormalized
				fmant = math.ldexp(fmant, expon)
				expon = 0
			expon = expon | sign
			fmant = math.ldexp(fmant, 32)
			fsmant = math.floor(fmant)
			himant = long(fsmant)
			fmant = math.ldexp(fmant - fsmant, 32)
			fsmant = math.floor(fmant)
			lomant = long(fsmant)
	_write_short(f, expon)
	_write_long(f, himant)
	_write_long(f, lomant)
开发者ID:asottile,项目名称:ancient-pythons,代码行数:32,代码来源:aifc.py

示例11: from_extents

 def from_extents(self, ulx, uly, lrx, lry):
   '''
   Set value from an extent tuple.
   For example, cairo extents, floats, inked, converted to DCS.
   
   !!! ulx may be greater than lrx, etc. due to transformations
   
   !!! Extents may be either path (ideal) or stroke (inked).
   The ideal extent of a line can have zero width or height.
   
   !!! User may zoom out enough that bounds approach zero,
   even equal zero?
   
   !!! Parameters are float i.e. fractional.
   Bounds are snapped to the outside pixel boundary.
   '''
   # Snap to integer boundaries and order on the number line.
   # !!! Note int(floor()) not just int()
   minxi = int(math.floor(min(ulx, lrx)))
   minyi = int(math.floor(min(uly, lry)))
   maxxi = int(math.ceil(max(ulx, lrx)))
   maxyi = int(math.ceil(max(uly, lry)))
   width = maxxi - minxi
   height = maxyi - minyi
   # width or height or both can be zero, for example setting transform on empty model
   
   # snap float rect to outside integral pixel
   ## self = gdk.Rectangle(minxi, minyi, width, height)
   self = Bounds(minxi, minyi, width, height)
   # not assert x,y positive
   # assert self.width >= 0  # since abs used
   if self.is_null():
     print "!!!!!!!!!!!! Null bounds", self
   return self
开发者ID:bootchk,项目名称:pensool,代码行数:34,代码来源:bounds.py

示例12: from_context_stroke

 def from_context_stroke(self, context):
   '''
   Get the DCS bounds of the path in the graphics context.
   Stroke, that is, as inked, not as ideal path.
   '''
   # extents of rect in UCS, aligned with axis
   ulx, uly, lrx, lry = context.stroke_extents() 
   # Two other corners of the rect
   llx = ulx
   lly = lry
   urx = lrx
   ury = uly
   # Four points in DCS, corners of rect NOT axis aligned,
   # and no relationships known between points in DCS
   p1xd, p1yd = context.user_to_device(ulx, uly)
   p2xd, p2yd = context.user_to_device(llx, lly)
   p3xd, p3yd = context.user_to_device(lrx, lry)
   p4xd, p4yd = context.user_to_device(urx, ury)
   # DCS bounds are min and max of device coords of all four points.
   # Snap to outside pixel using floor, ceiling.
   # Convert to int
   minxi = int(math.floor(min(p1xd, p3xd, p2xd, p4xd)))
   minyi = int(math.floor(min(p1yd, p3yd, p2yd, p4yd)))
   maxxi =  int(math.ceil(max(p1xd, p3xd, p2xd, p4xd)))
   maxyi =  int(math.ceil(max(p1yd, p3yd, p2yd, p4yd)))
   width = maxxi - minxi
   height = maxyi - minyi
   self = Bounds(minxi, minyi, width, height)
   # !!! Cannot assert not is_null: line width tiny or other factors
   # may yield empty stroke extents.
   return self
开发者ID:bootchk,项目名称:pensool,代码行数:31,代码来源:bounds.py

示例13: interpolate_cartesian

    def interpolate_cartesian(self, start_pos, start_rot, end_pos, end_rot, pos_spacing, rot_spacing, num_steps = 0):

        #normalize quaternion rotations just in case
        norm_start_rot = self.normalize_vect(start_rot)
        norm_end_rot = self.normalize_vect(end_rot)

        #the desired wrist translation
        diff = [x-y for (x,y) in zip(end_pos, start_pos)]

        if num_steps == 0:
            #compute how far the wrist translates
            pos_move = self.vect_norm(diff)

            #compute how far the wrist rotates
            rot_move = self.quat_angle(norm_start_rot, norm_end_rot)

            #compute the number of steps to move no more than pos_spacing and rot_spacing in each step
            #(min 2, start and end)
            num_steps_pos = math.floor(pos_move/pos_spacing)+1
            num_steps_rot = math.floor(rot_move/rot_spacing)+1
            num_steps = int(max([num_steps_pos, num_steps_rot])+1)  
        
        #interpolate
        steps = []
        for stepind in range(num_steps):
            fraction = float(stepind)/(num_steps-1)  #add both start (0) and end (1)
            rot = list(tf.transformations.quaternion_slerp(norm_start_rot, norm_end_rot, fraction))
            pos = list(numpy.array(diff)*fraction + numpy.array(start_pos))
            steps.append((pos, rot))
            #print "fraction: %5.3f"%fraction, "pos:", pplist(pos), "rot:", pplist(rot)

        return steps
开发者ID:abubeck,项目名称:cob_object_manipulation,代码行数:32,代码来源:ik_utilities.py

示例14: from_jd

    def from_jd(cls, jd):
        """
            Convert a Julian day number to a year/month/day tuple
            of this calendar (matching jQuery calendars algorithm)

            @param jd: the Julian day number
        """

        jd = math.floor(jd) + 0.5;

        depoch = jd - cls.to_jd(475, 1, 1)

        cycle = math.floor(depoch / 1029983)
        cyear = math.fmod(depoch, 1029983)

        if cyear != 1029982:
            aux1 = math.floor(cyear / 366)
            aux2 = math.fmod(cyear, 366)
            ycycle = math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1
        else:
            ycycle = 2820

        year = ycycle + (2820 * cycle) + 474
        if year <= 0:
            year -= 1

        yday = jd - cls.to_jd(year, 1, 1) + 1
        if yday <= 186:
            month = math.ceil(yday / 31)
        else:
            month = math.ceil((yday - 6) / 30)

        day = jd - cls.to_jd(year, month, 1) + 1

        return (int(year), int(month), int(day))
开发者ID:jfmnet,项目名称:eden,代码行数:35,代码来源:s3datetime.py

示例15: divideRect

    def divideRect( self, x, y, width, height, c1, c2, c3, c4 ):
        new_width = math.floor( width / 2 )
        new_height = math.floor( height / 2 )

        if ( width > 1 or height > 1 ):
            # average of all the points and normalize in case of "out of bounds" during displacement
            mid = self.normalize( self.normalize( ( ( c1 + c2 + c3 + c4 ) / 4 ) + self.displace( new_width + new_height ) ) )

            # midpoint of the edges is the average of its two end points
            edge1 = self.normalize( ( c1 + c2 ) / 2 )
            edge2 = self.normalize( ( c2 + c3 ) / 2 )
            edge3 = self.normalize( ( c3 + c4 ) / 2 )
            edge4 = self.normalize( ( c4 + c1 ) / 2 )

            # recursively go down the rabbit hole
            self.divideRect( x, y, new_width, new_height, c1, edge1, mid, edge4 )
            self.divideRect( x + new_width, y, new_width, new_height, edge1, c2, edge2, mid )
            self.divideRect( x + new_width, y + new_height, new_width, new_height, mid, edge2, c3, edge3 )
            self.divideRect( x, y + new_height, new_width, new_height, edge4, mid, edge3, c4 )

        else:
            c = ( c1 + c2 + c3 + c4 ) / 4

            self.heightmap[x][y] = c

            if ( width == 2 ):
                self.heightmap[x + 1][y] = c
            if ( height == 2 ):
                self.heightmap[x][y + 1] = c
            if ( width == 2 and height == 2 ):
                self.heightmap[x + 1][y + 1] = c
开发者ID:dplepage,项目名称:worldsynth,代码行数:31,代码来源:midpointDisplacement.py


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