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


Python float函数代码示例

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


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

示例1: do_padding

def do_padding(img, padding):
    if not padding:
        return img
    try:
        padding = float(padding)*2.0
        if padding > .9:
            padding = .9
        if padding <= 0.0:
            return img
    except ValueError:
        return

    iw, ih = img.size

    img.thumbnail(
        (
            int( round( float(img.size[0]) * (1.0 - padding) ) ),
            int( round( float(img.size[1]) * (1.0 - padding) ) )
        ),
        pil.ANTIALIAS
        )

    img = do_fill(img, "ffffff00", iw, ih)

    return img
开发者ID:Michael2011,项目名称:code-note,代码行数:25,代码来源:utils.py

示例2: calc_pr

def calc_pr(bigccmat, numnodes, pprloc=-99):
    """
    function calc_pr calculates PageRank based on the input transition matrix
    """
    # convert to transition matrix
    rowsum = bigccmat.sum(axis=1)
    for ii in range(numnodes):
        if rowsum[ii, 0] != 0:
            bigccmat[ii, :] = bigccmat[ii, :] / rowsum[ii, 0]
        else:
            # case with no outgoing links
            bigccmat[ii, ii] = 1.0

    # convert sparse matrix format
    sp_transmat_first = scisp.csr_matrix(bigccmat)
    oldprvec = np.matrix(np.ones((numnodes, 1))) / float(numnodes)
    convergevec = [1000]  # some large value
    if pprloc > 0:
        onevec = np.matrix(np.zeros((numnodes, 1)))
        onevec[pprloc, 0] = 0.15
    else:
        onevec = (0.15 / float(numnodes)) * np.matrix(np.ones((numnodes, 1)))
    ii = 0
    while convergevec[-1] > 1e-5:
        newprvec = 0.85 * (sp_transmat_first.T * oldprvec)
        newprvec = newprvec + onevec
        newnorm = np.linalg.norm(newprvec, 1)
        convergevec.append(sum(abs(newprvec - oldprvec))[0, 0])
        oldprvec = newprvec
        ii = ii + 1
    print "Norm of PR vector:", newnorm
    print "Number of iterations for convergence:", ii
    convergevec.remove(1000)
    return (newprvec, convergevec)
开发者ID:neocsbee,项目名称:Utils,代码行数:34,代码来源:pagerank.py

示例3: from_pmml

def from_pmml(self, pmml):
    """Returns a model with the intercept and coefficients represented in PMML file."""

    model = self()
    
    # Reads the input PMML file with BeautifulSoup.
    with open(pmml, "r") as f:
        lm_soup = BeautifulSoup(f, "xml")

    if not lm_soup.RegressionTable:
        raise ValueError("RegressionTable not found in the input PMML file.")

    else:
    ##### DO I WANT TO PULL THIS OUT AS ITS OWN FUNCTION? #####
        # Pulls out intercept from the PMML file and assigns it to the
        # model. If the intercept does not exist, assign it to zero.
        intercept = 0
        if "intercept" in lm_soup.RegressionTable.attrs:
            intercept = lm_soup.RegressionTable['intercept']
        model.intercept_ = float(intercept)

        # Pulls out coefficients from the PMML file, and assigns them
        # to the model.
        if not lm_soup.find_all('NumericPredictor'):
            raise ValueError("NumericPredictor not found in the input PMML file.")
        else:
            coefs = []
            numeric_predictors = lm_soup.find_all('NumericPredictor')
            for i in numeric_predictors:
                i_coef = float(i['coefficient'])
                coefs.append(i_coef)
            model.coef_ = numpy.array(coefs)
            
    return model
开发者ID:jeenalee,项目名称:sklearn_pmml,代码行数:34,代码来源:linear_regression.py

示例4: getCraftedGcode

	def getCraftedGcode(self, fileName, repository, svgText):
		"Parse svgText and store the scale svgText."
		svgReader = SVGReader()
		svgReader.parseSVG('', svgText)
		if svgReader.sliceDictionary == None:
			print('Warning, nothing will be done because the sliceDictionary could not be found getCraftedGcode in preface.')
			return ''
		xyPlaneScale = repository.xyPlaneScale.value
		zAxisScale = repository.zAxisScale.value
		decimalPlacesCarried = int(svgReader.sliceDictionary['decimalPlacesCarried'])
		layerHeight = zAxisScale * float(svgReader.sliceDictionary['layerHeight'])
		edgeWidth = float(svgReader.sliceDictionary['edgeWidth'])
		loopLayers = svgReader.loopLayers
		for loopLayer in loopLayers:
			setLoopLayerScale(loopLayer, xyPlaneScale, zAxisScale)
		cornerMaximum = Vector3(-912345678.0, -912345678.0, -912345678.0)
		cornerMinimum = Vector3(912345678.0, 912345678.0, 912345678.0)
		svg_writer.setSVGCarvingCorners(cornerMaximum, cornerMinimum, layerHeight, loopLayers)
		svgWriter = svg_writer.SVGWriter(
			True,
			cornerMaximum,
			cornerMinimum,
			decimalPlacesCarried,
			layerHeight,
			edgeWidth)
		commentElement = svg_writer.getCommentElement(svgReader.documentElement)
		procedureNameString = svgReader.sliceDictionary['procedureName'] + ',scale'
		return svgWriter.getReplacedSVGTemplate(fileName, loopLayers, procedureNameString, commentElement)
开发者ID:folksjos,项目名称:RepG,代码行数:28,代码来源:scale.py

示例5: find_info

def find_info(test):
	#do the match
	match = regex.match(test)
	if match is not None:
		return (match.group(1),float(match.group(2)),float(match.group(3)),float(match.group(4)))
	else:
		return ("",0,0,0)
开发者ID:XuezhuLi,项目名称:baseball-stat-counter,代码行数:7,代码来源:counters.py

示例6: __init__

	def __init__(self):
		rospy.init_node('actuators_handler')
		rospy.loginfo(rospy.get_caller_id() + 'Initializing actuators_handler node')

		self.timelast = 0

		#Get all parameters from config (rosparam)
		name = 'engine'
		engine_output_pin = int(rospy.get_param('actuators/' + name + '/output_pin', 1))
		engine_board_pin = int(rospy.get_param('actuators/' + name + '/board_pin', 60))
		engine_period_us = int(1e6 / float(rospy.get_param('actuators/' + name + '/frequency', 60)))

		name = 'steering'
		steering_output_pin = int(rospy.get_param('actuators/' + name + '/output_pin', 1))
		steering_board_pin = int(rospy.get_param('actuators/' + name + '/board_pin', 62))
		steering_period_us = int(1e6 / float(rospy.get_param('actuators/' + name + '/frequency', 60)))

		#Initialize PWM
		self.dev1 = mraa.Pwm(engine_board_pin)
		self.dev1.period_us(engine_period_us)
		self.dev1.enable(True)
		self.dev1.pulsewidth_us(1500)

		self.dev2 = mraa.Pwm(steering_board_pin)
		self.dev2.period_us(steering_period_us)
		self.dev2.enable(True)
		self.dev2.pulsewidth_us(1500)
开发者ID:Omyk,项目名称:Data_BBB8,代码行数:27,代码来源:actuator_sub_pid.py

示例7: set_value

	def set_value(self, value):
		if(self._parameter_to_map_to != None):
			if(self._parameter_to_map_to.is_enabled):
				newval = float(float(float(value)/127) * (self._parameter_to_map_to.max - self._parameter_to_map_to.min)) + self._parameter_to_map_to.min
				self._parameter_to_map_to.value = newval
		else:
			self.receive_value(int(value))
开发者ID:LividInstruments,项目名称:LiveRemoteScripts,代码行数:7,代码来源:CodecEncoderElement.py

示例8: parse_rho

def parse_rho(m1, m2, config):
    """Parse the rho data and convert to numpy array."""
    f = open(in_name(m1, m2, config), 'r')
    
    # Skip to the mixed rho correlator section.
    # This assumes it is the first RHO* entry. !!
    x = f.readline()
    while x:
        if re.match('correlator:\s+RHO', x):
            break
        x = f.readline()

    # Throw away header.
    print x
    for i in range(5):
        print f.readline().strip()

    result = []
    for i in range(64):
        t, r, im = f.readline().strip().split('\t')
        result.append(complex(float(r), float(im)))        
    
    f.close()

    return np.array(result)
开发者ID:atlytle,项目名称:tifr,代码行数:25,代码来源:parse_mixed.py

示例9: testcaserun_setstatus

def testcaserun_setstatus(request, testcaserun_id):
    testcaserun = TestCaseRun.objects.get(pk=testcaserun_id)
    testcaserun_status_form = forms.TestCaseRunStatus(request.POST, instance=testcaserun)
    if testcaserun_status_form.is_valid():
        testcaserun = testcaserun_status_form.save()

        log = history.History(request.user, testcaserun.parent)
        log.add_form(testcaserun_status_form, capture=["status"], prefix=True)
        log.save()

        # TODO: move this to testrun? method. Chec also templatetags
        passrate_ratio = []
        testrun = testcaserun.parent
        testcaseruns_count = testrun.testcases.count()
        statuses = TestCaseRunStatus.objects.filter(testcaserun__parent=testrun).annotate(count=Count('testcaserun'))
        for status in statuses:
            passrate_ratio.append({
                "ratio": float(status.count) / float(testcaseruns_count) * 100,
                "name": status.name,
                "color": status.color,
                })

        return success(message=testcaserun.status.name,
                       data=dict(id=testcaserun.pk,
                                 name=testcaserun.status.name,
                                 color=testcaserun.status.color,
                                 passrate=testcaserun.parent.passrate,
                                 passrate_ratio=passrate_ratio))
    else:
        return failed(message=testcaserun.status.name,
                      data=testcaserun_status_form.errors_list())
开发者ID:sliwa,项目名称:qualitio,代码行数:31,代码来源:views.py

示例10: _render_on_subplot

    def _render_on_subplot(self, subplot):
        """
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES::

        This function implicitly ends up rendering this arrow on a matplotlib subplot:
            sage: arrow(path=[[(0,1), (2,-1), (4,5)]])
        """
        options = self.options()
        width = float(options['width'])
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')
        arrowsize = float(options.get('arrowsize',5))
        head_width=arrowsize
        head_length=arrowsize*2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        from matplotlib.path import Path
        bpath = Path(self.vertices, self.codes)
        p = FancyArrowPatch(path=bpath,
                            lw=width, arrowstyle='%s,head_width=%s,head_length=%s'%(style,head_width, head_length), 
                            fc=color, ec=color, linestyle=options['linestyle'])
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])
        subplot.add_patch(p)
        return p
开发者ID:pombredanne,项目名称:sage-1,代码行数:32,代码来源:arrow.py

示例11: legIK

    def legIK(self, X, Y, Z, resolution):
        """ Compute leg servo positions. """
        ans = [0,0,0,0]    # (coxa, femur, tibia)
       
        try:
            # first, make this a 2DOF problem... by solving coxa
            ans[0] = radToServo(atan2(X,Y), resolution)
            trueX = int(sqrt(sq(X)+sq(Y))) - self.L_COXA
            im = int(sqrt(sq(trueX)+sq(Z)))  # length of imaginary leg
            
            # get femur angle above horizon...
            q1 = -atan2(Z,trueX)
            d1 = sq(self.L_FEMUR)-sq(self.L_TIBIA)+sq(im)
            d2 = 2*self.L_FEMUR*im
            q2 = acos(d1/float(d2))
            ans[1] = radToServo(q1+q2, resolution)  
        
            # and tibia angle from femur...
            d1 = sq(self.L_FEMUR)-sq(im)+sq(self.L_TIBIA)
            d2 = 2*self.L_TIBIA*self.L_FEMUR;
            ans[2] = radToServo(acos(d1/float(d2))-1.57, resolution)
        except:
            if self.debug:
                "LegIK FAILED"
            return [1024,1024,1024,0]

        if self.debug:
            print "LegIK:",ans
        return ans
开发者ID:IanMHoffman,项目名称:pypose,代码行数:29,代码来源:lizard3.py

示例12: send_file_multicast

    def send_file_multicast(s, filename):
        connections = {}
        filesize = os.stat(filename).st_size
        try:
            while True:
                readable, _, _ = select.select([s], [], [])
                for rd in readable:
                    bytes_sent = 0
                    package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE)
                    unpacked_package = Utils.unpack_package(package)

                    if not connections.has_key(client_address) or connections[client_address] is None:
                        connections[client_address] = open(filename, 'rb')

                    if unpacked_package['command'] == Constants.INIT_TRANSMIT:
                        bytes_sent = int(unpacked_package['payload'])
                        connections[client_address].seek(bytes_sent)
                        data = connections[client_address].read(Constants.FILE_CHUNK_SIZE)
                        if not data:
                            rd.sendto(Utils.pack_package(Constants.FIN, ''), client_address)
                            connections[client_address].close()
                            connections[client_address] = None
                        else:
                            rd.sendto(Utils.pack_package(Constants.ACK, data), client_address)

                    bytes_sent += len(data)
                    percent = int(float(bytes_sent) * 100 / float(filesize))

                    print "{0} / {1} Kb sent to client {2}({3}%)".format(Utils.to_kilobytes(bytes_sent),
                                                                         Utils.to_kilobytes(filesize), client_address,
                                                                         percent)
                    sys.stdout.write('\033M')

        except socket.error, value:
            print value
开发者ID:VadzimBura,项目名称:SPOLKS,代码行数:35,代码来源:file_transmitter.py

示例13: send_file_with_oob_tcp

    def send_file_with_oob_tcp(s, filename):
        sending_file = open(filename, 'rb')
        filesize = os.stat(filename).st_size
        oob_sent = 0
        try:
            bytes_sent = int(s.recv(Constants.FILE_CHUNK_SIZE))
            print "Already sent {0} / {1}".format(bytes_sent, filesize)
        except:
            print 'Lost Connection'
            return 0
        sending_file.seek(int(bytes_sent), 0)

        while True:
            chunk = sending_file.read(Constants.FILE_CHUNK_SIZE)
            if not chunk:
                break
            try:
                s.settimeout(Constants.DEFAULT_TIMEOUT)
                s.send(chunk)
            except socket.error:
                print 'Transfer fail'
                return 0
            bytes_sent += Constants.FILE_CHUNK_SIZE
            percent = int(float(bytes_sent) * 100 / float(filesize))
            print "{0} / {1} Kb sent ({2}%)".format(Utils.to_kilobytes(bytes_sent),
                                                    Utils.to_kilobytes(filesize), percent)
            sys.stdout.write('\033M')
            if (percent % 10 == 0) & (oob_sent != percent) & (percent < 91):
                oob_sent = percent
                sys.stdout.write('\033D')
                print '\033[37;1;41m Urgent flag sent at {0}% \033[0m'.format(percent)
                s.send(b'{}'.format(percent / 10), socket.MSG_OOB)

        sending_file.close()
开发者ID:VadzimBura,项目名称:SPOLKS,代码行数:34,代码来源:file_transmitter.py

示例14: send_file_udp

    def send_file_udp(s, filename):
        bytes_sent = 0

        sending_file = open(filename, 'rb')
        filesize = os.stat(filename).st_size

        while True:
            package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE)
            unpacked_package = Utils.unpack_package(package)

            if unpacked_package['command'] == Constants.INIT_TRANSMIT:
                bytes_sent = int(unpacked_package['payload'])
                sending_file.seek(bytes_sent)
                data = sending_file.read(Constants.FILE_CHUNK_SIZE)
                if not data:
                    s.sendto(Utils.pack_package(Constants.FIN, ''), client_address)
                    sending_file.close()
                    break
                else:
                    s.sendto(Utils.pack_package(Constants.ACK, data), client_address)

            package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE)
            unpacked_package = Utils.unpack_package(package)

            if unpacked_package['command'] == Constants.ACK:
                bytes_sent += len(data)
                percent = int(float(bytes_sent) * 100 / float(filesize))

                print "{0} / {1} Kb sent ({2}%)".format(Utils.to_kilobytes(bytes_sent),
                                                        Utils.to_kilobytes(filesize), percent)
开发者ID:VadzimBura,项目名称:SPOLKS,代码行数:30,代码来源:file_transmitter.py

示例15: init

def init():
    global theMesh,  theLight, theCamera, \
           theScreen,    resolution
    initializeVAO()
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)

    # Add our object
    # LIGHT
    theLight = N.array((-0.577, 0.577, 0.577, 0.0),dtype=N.float32)
    # OBJECT
    phongshader = makeShader("phongshader.vert","phongshader.frag")
    verts, elements = readOBJ("suzanne.obj")
    suzanneVerts = getArrayBuffer(verts)
    suzanneElements = getElementBuffer(elements)
    suzanneNum = len(elements)
    theMesh = coloredMesh(N.array((1.0, 0.5, 1.0, 1.0), dtype=N.float32),
                          suzanneVerts,
                          suzanneElements,
                          suzanneNum,
                          phongshader)

    # CAMERA
    width,height = theScreen.get_size()
    aspectRatio = float(width)/float(height)
    near = 0.01
    far = 100.0
    lens = 4.0  # "longer" lenses mean more telephoto
    theCamera = Camera(lens, near, far, aspectRatio)
    theCamera.moveBack(6)
开发者ID:geo7,项目名称:csci480,代码行数:30,代码来源:gm121.py


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