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


Python abs函数代码示例

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


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

示例1: getDist

 def getDist(self):
     mainCharX = self.mainChar.getPos().x
     mainCharY = self.mainChar.getPos().y
     pandaX = self.pandaActor2.getPos().x
     pandaY = self.pandaActor2.getPos().y
     dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2)
     return dist
开发者ID:genusgant,项目名称:CS594-ThrottleThunder-GameClient,代码行数:7,代码来源:RRMain.py

示例2: get_ruler_distances

    def get_ruler_distances(self, x1, y1, x2, y2):
        mode = self.t_drawparams.get('units', 'arcmin')
        try:
            image = self.fitsimage.get_image()
            if mode == 'arcmin':
                # Calculate RA and DEC for the three points
                # origination point
                ra_org, dec_org = image.pixtoradec(x1, y1)

                # destination point
                ra_dst, dec_dst = image.pixtoradec(x2, y2)

                # "heel" point making a right triangle
                ra_heel, dec_heel = image.pixtoradec(x2, y1)

                text_h = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_dst, dec_dst)
                text_x = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_heel, dec_heel)
                text_y = image.get_starsep_RaDecDeg(ra_heel, dec_heel, ra_dst, dec_dst)
            else:
                dx = abs(x2 - x1)
                dy = abs(y2 - y1)
                dh = math.sqrt(dx**2 + dy**2)
                text_x = str(dx)
                text_y = str(dy)
                text_h = ("%.3f" % dh)
                
        except Exception, e:
            text_h = 'BAD WCS'
            text_x = 'BAD WCS'
            text_y = 'BAD WCS'
开发者ID:PaulPrice,项目名称:ginga,代码行数:30,代码来源:FitsImageCanvas.py

示例3: test_scal

def test_scal(vector_array):
    v = vector_array
    for ind in valid_inds(v):
        if v.len_ind(ind) != v.len_ind_unique(ind):
            with pytest.raises(Exception):
                c = v.copy()
                c[ind].scal(1.)
            continue
        ind_complement_ = ind_complement(v, ind)
        c = v.copy()
        c[ind].scal(1.)
        assert len(c) == len(v)
        assert np.all(almost_equal(c, v))

        c = v.copy()
        c[ind].scal(0.)
        assert np.all(almost_equal(c[ind], v.zeros(v.len_ind(ind))))
        assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))

        for x in (1., 1.4, np.random.random(v.len_ind(ind))):
            c = v.copy()
            c[ind].scal(x)
            assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))
            assert np.allclose(c[ind].sup_norm(), v[ind].sup_norm() * abs(x))
            assert np.allclose(c[ind].l2_norm(), v[ind].l2_norm() * abs(x))
            if hasattr(v, 'data'):
                y = v.data.copy()
                if NUMPY_INDEX_QUIRK and len(y) == 0:
                    pass
                else:
                    if isinstance(x, np.ndarray) and not isinstance(ind, Number):
                        x = x[:, np.newaxis]
                    y[ind] *= x
                assert np.allclose(c.data, y)
开发者ID:renemilk,项目名称:pyMor,代码行数:34,代码来源:vectorarray.py

示例4: defaultGait

    def defaultGait(self,leg):        
        # just walk forward for now
        travelX = 50
        travelY = 0
        travelRotZ = 0

        if abs(travelX)>5 or abs(travelY)>5 or abs(travelRotZ) > 0.05:   # are we moving?
            if(self.order[leg] == self.step):
                # up, middle position                    
                self[leg][0] = 0        # x
                self[leg][1] = 0        # y
                self[leg][2] = -20      # z
                self[leg][3] = 0        # r
            elif (self.order[leg]+1 == self.step) or (self.order[leg]-7 == self.step):   # gaits in step -1 
                # leg down!                    
                self[leg][0] = travelX/2
                self[leg][1] = travelY/2
                self[leg][2] = 0       
                self[leg][3] = travelRotZ/2      
            else:
                # move body forward 
                self[leg][0] = self[leg][0] - travelX/6
                self[leg][1] = self[leg][1] - travelY/6
                self[leg][2] = 0       
                self[leg][3] = self[leg][3] - travelRotZ/6    
        return self[leg]
开发者ID:IanMHoffman,项目名称:pypose,代码行数:26,代码来源:lizard3.py

示例5: demoNoiseWS

def demoNoiseWS(iteration=11):
    print("reading image...")
    image = readImage('../samples/monsters.png', grayScale=True)
    adj4 = AdjacencyNdRegular.getAdjacency2d4(image.embedding.size)
    image = rescaleGray(image, 0, 1)
    convolve = False
    noiseInImage = True
    sal0 = None
    for i in range(iteration):
        print("-> Iteration " + str(i))
        print("Constructing gradient graph...")
        if noiseInImage:
            im2 = imageMap(image, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=False)
            adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(im2[i] - im2[j]))
        else:
            adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(image[i] - image[j]))
            adjacency = imageMap(adjacency, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=True)


        print("Constructing area watershed...")
        # wsh = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(adjacency))
        # addAttributeArea(wsh)
        # wsha= transformBPTtoAttributeHierarchy(wsh,"area")
        wsha = constructExactRandomSeedsWatershed(adjacency)
        sal = computeSaliencyMapFromAttribute(wsha, adj4)

        print("Averaging and Drawing saliency...")
        if convolve:
            lineGraph = WeightedAdjacency.createLineGraph(sal)
            adjLineGraph = WeightedAdjacency.createReflexiveRelation(lineGraph)
            meanSal = spatialFilter(sal, adjLineGraph, BasicAccumulator.getMeanAccumulator())
        else:
            meanSal = sal

        saveImage(normalizeToByte(
            imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, meanSal), 0, 1), lambda x: x ** 0.33333)),
            "Results/Random noise gradient " + str(i) + ".png")
        if sal0 is None:
            sal0 = meanSal
            for j in range(len(sal0)):
                sal0[j] = [sal0[j]]
        else:
            for j in range(len(sal0)):
                sal0[j].append(meanSal[j])
    print("Merging results...")

    for i in range(len(sal0)):
        sal0[i] = meanV(sal0[i])

    saveImage(normalizeToByte(
        imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, sal0), 0, 1), lambda x: x ** 0.33333)),
        "Results/Random noise combined gradient.png")

    print("Ultra metric opening...")
    bpt = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(sal0))
    addAttributeArea(bpt)

    nbpt = filterBPTbyCriterion(bpt, lambda i: min(bpt.area[bpt.children[i][0]], bpt.area[bpt.children[i][1]]) < 10)
    saveImage(drawSaliencyForVisualisation(bpt, image), "Results/Random noise WS bpt.png")
    saveImage(drawSaliencyForVisualisation(nbpt, image), "Results/Random noise WS filteredbpt.png")
开发者ID:PerretB,项目名称:HiPy,代码行数:60,代码来源:DemoStochasticWatershed.py

示例6: test

def test():
    '''Test the basic workings of `parse_slice`.'''
    
    r1 = range(5)
    r2 = range(2, 10)
    r3 = range(100, 3, -7)
    ranges = [r1, r2, r3]
    
    slices = [slice(3), slice(5), slice(9), slice(1, 4), slice(4, 7),
              slice(6, 2), slice(1, 4, 1), slice(1, 5, 3), slice(6, 2, 3),
              slice(6, 2, -3),  slice(8, 2, -1), slice(2, 5, -2),
              slice(None, 5, -2), slice(6, None, -2), slice(8, 4, None),
              slice(None, None, -2)]
    
    for slice_ in slices:
        (start, stop, step) = parse_slice(slice_)
        
        # Replacing `infinity` with huge number cause Python's lists can't
        # handle `infinity`:
        if abs(start) == infinity: start = 10**10 * math_tools.get_sign(start)
        if abs(stop) == infinity: stop = 10**10 * math_tools.get_sign(stop)
        if abs(step) == infinity: step = 10**10 * math_tools.get_sign(step)
        #######################################################################
            
        assert [start, stop, step].count(None) == 0
        
        parsed_slice = slice(start, stop, step)
        for range_ in ranges:
            assert range_[slice_] == range_[parsed_slice]
开发者ID:rfdiazpr,项目名称:python_toolbox,代码行数:29,代码来源:test_parse_slice.py

示例7: mouseInput

def mouseInput():    
    
    cont = logic.getCurrentController()
    owner = cont.owner 
    
    centerX = (render.getWindowWidth()//2)/render.getWindowWidth()
    centerY = (render.getWindowHeight()//2)/render.getWindowHeight()
    
    global oldMouseVec
    if oldMouseVec == None:
        oldMouseVec = mathutils.Vector([0.0,0.0])
        logic.mouse.position = (centerX,centerY)
        return mathutils.Vector([0,0])
            
    x = logic.mouse.position[0] - centerX
    if abs(x) < abs(2/render.getWindowWidth()): x = 0
    y = centerY - logic.mouse.position[1]
    if abs(y) < abs(2/render.getWindowWidth()): y = 0
    newMouseVec = mathutils.Vector([x, y])  
    
    global mouseSensitivity 
    
    newMouseVec *= mouseSensitivity
    
    # Smooth movement
    global mouseSmooth
    
    oldMouseVec = oldMouseVec*mouseSmooth + newMouseVec*(1.0-mouseSmooth)
    newMouseVec = oldMouseVec
    
    # Center mouse in game window
    logic.mouse.position = (centerX,centerY)    
    
    return mathutils.Vector(newMouseVec)
开发者ID:elfnor,项目名称:mazes,代码行数:34,代码来源:Input.py

示例8: getPartInfo

def getPartInfo( part ):
        points = part['points']
        n = len(points)
        area = cx = cy = 0
        xmin = ymin = 360
        xmax = ymax = -360
        pt = points[n-1];  xx = pt[0];  yy = pt[1]
        for pt in points:
                x = pt[0];  y = pt[1]
                # bounds
                xmin = min( x, xmin );  ymin = min( y, ymin )
                xmax = max( x, xmax );  ymax = max( y, ymax )
                # area and centroid
                a = xx * y - x * yy
                area += a
                cx += ( x + xx ) * a
                cy += ( y + yy ) * a
                # next
                xx = x;  yy = y
        area /= 2
        if area:
                centroid = [ cx / area / 6, cy / area / 6 ]
        else:
                centroid = None
        part.update({
                'area': abs(area),
                'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ],
                'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ],
                'centroid': centroid,
                'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ]
        })
开发者ID:shangyian,项目名称:greatlakes-call-data,代码行数:31,代码来源:shpUtils.py

示例9: to_polynomial

    def to_polynomial(self, c):
        """
        Convert clause to :class:`sage.rings.polynomial.pbori.BooleanPolynomial`

        INPUT:

        - ``c`` - a clause

        EXAMPLE::

            sage: B.<a,b,c> = BooleanPolynomialRing()
            sage: from sage.sat.converters.polybori import CNFEncoder
            sage: from sage.sat.solvers.dimacs import DIMACS
            sage: fn = tmp_filename()
            sage: solver = DIMACS(filename=fn)
            sage: e = CNFEncoder(solver, B, max_vars_sparse=2)
            sage: _ = e([a*b + a + 1, a*b+ a + c])
            sage: e.to_polynomial( (1,-2,3) )
            a*b*c + a*b + b*c + b
        """
        def product(l):
            # order of these multiplications for performance
            res = l[0]
            for p in l[1:]:
                res = res*p
            return res

        phi = self.phi
        product = self.ring(1)
        for v in c:
            if phi[abs(v)] is None:
                raise ValueError("Clause containst an XOR glueing variable.")
            product *= phi[abs(v)] + int(v>0)
        return product
开发者ID:DrXyzzy,项目名称:sage,代码行数:34,代码来源:polybori.py

示例10: fit_CSU_edges

def fit_CSU_edges(profile):
    fitter = fitting.LevMarLSQFitter()

    amp1_est = profile[profile == min(profile)][0]
    mean1_est = np.argmin(profile)
    amp2_est = profile[profile == max(profile)][0]
    mean2_est = np.argmax(profile)
    
    g_init1 = models.Gaussian1D(amplitude=amp1_est, mean=mean1_est, stddev=2.)
    g_init1.amplitude.max = 0
    g_init1.amplitude.min = amp1_est*0.9
    g_init1.stddev.max = 3
    g_init2 = models.Gaussian1D(amplitude=amp2_est, mean=mean2_est, stddev=2.)
    g_init2.amplitude.min = 0
    g_init2.amplitude.min = amp2_est*0.9
    g_init2.stddev.max = 3

    model = g_init1 + g_init2
    fit = fitter(model, range(0,profile.shape[0]), profile)
    
    # Check Validity of Fit
    if abs(fit.stddev_0.value) <= 3 and abs(fit.stddev_1.value) <= 3\
       and fit.amplitude_0.value < -1 and fit.amplitude_1.value > 1\
       and fit.mean_0.value > fit.mean_1.value:
        x = [fit.mean_0.value, fit.mean_1.value]
        x1 = int(np.floor(min(x)-1))
        x2 = int(np.ceil(max(x)+1))
    else:
        x1 = None
        x2 = None

    return x1, x2
开发者ID:joshwalawender,项目名称:KeckUtilities,代码行数:32,代码来源:slitAlign.py

示例11: karatsuba_multiply

def karatsuba_multiply(x, y):
  if x == 0 or y == 0: return 0
  sign = 1
  if (x < 0 and y > 0) or (x > 0 and y < 0): sign = -1
  x = abs(x)
  y = abs(y)
  max_digit = max(x.bit_length(), y.bit_length())

  if max_digit == 1: return 1

  half_digit = max_digit // 2
  filter_mask = (1 << half_digit) - 1

  x_upper_half = x >> half_digit
  x_lower_half = x & filter_mask
  y_upper_half = y >> half_digit
  y_lower_half = y & filter_mask

  z_0 = karatsuba_multiply(x_lower_half, y_lower_half)
  z_2 = karatsuba_multiply(x_upper_half, y_upper_half)
  z_1 = karatsuba_multiply((x_lower_half + x_upper_half), (y_lower_half + y_upper_half)) - z_0 - z_2

  abs_res = ((z_2  << half_digit << half_digit) +
          (z_1 << half_digit) +
          z_0)
  if sign == -1: return ~abs_res + 1
  else: return abs_res
开发者ID:fikriauliya,项目名称:CS6.006,代码行数:27,代码来源:integer_arithmetic.py

示例12: test_translational_alignment

    def test_translational_alignment(self):
        """ Test the translational alignment in 2D routine """
        random.seed()
        name=self.get_input_file_name("1z5s-projection-2.spi")
        srw = IMP.em2d.SpiderImageReaderWriter()
        image=IMP.em2d.Image()
        image.read(name,srw)
        translated=IMP.em2d.Image()
        # random translation
        trans=IMP.algebra.Vector2D(random.random()*10,random.random()*10)
        transformation = IMP.algebra.Transformation2D(trans)
        IMP.em2d.get_transformed(image.get_data(),translated.get_data(),
                                 transformation)
        fn_translated = self.get_input_file_name("translated.spi")
#        translated.write(fn_translated,srw)
        result=IMP.em2d.get_translational_alignment(
                image.get_data(),translated.get_data(),True)
        fn_aligned = self.get_input_file_name("trans_aligned.spi")
 #       translated.write(fn_aligned,srw)
        # -1 to get the translation applied to reference.
        # Result contains the translation required for align the second matrix
        determined_trans= (-1)*result[0].get_translation()
        # Tolerate 1 pixel error
        self.assertAlmostEqual(abs(determined_trans[0]-trans[0]),0, delta=1,
                msg="1st coordinate is incorrect: Applied %f Determined %f" \
                    % (trans[0], determined_trans[0]))
        self.assertAlmostEqual(abs(determined_trans[1]-trans[1]),0, delta=1,
                msg="2nd coordinate is incorrect: Applied %f Determined %f" \
                    % (trans[1], determined_trans[1]))
开发者ID:andreyto,项目名称:imp-fork-proddl,代码行数:29,代码来源:test_align2d.py

示例13: test_rotational_alignment

    def test_rotational_alignment(self):
        """ Test the rotational alignment in 2D routine (new) """
        random.seed()
        name=self.get_input_file_name("1z5s-projection-2.spi")
        srw = IMP.em2d.SpiderImageReaderWriter()
        image=IMP.em2d.Image()
        image.read(name,srw)
        rotated=IMP.em2d.Image()
        # random rotation
        angle=random.random()*2*pi
        rot=IMP.algebra.Rotation2D(angle)
        transformation = IMP.algebra.Transformation2D(rot)
        IMP.em2d.get_transformed(image.get_data(),rotated.get_data(),
                                 transformation)

        fn_rotated = self.get_input_file_name("rotated.spi")
#        rotated.write(fn_rotated,srw)
        result=IMP.em2d.get_rotational_alignment(
                image.get_data(),rotated.get_data(),True)
        fn_aligned = self.get_input_file_name("rot_aligned.spi")
 #       rotated.write(fn_aligned,srw)
        determined_angle=result[0].get_rotation().get_angle()
        # approximately 6 degrees tolerance, 0.1 rad.
        x = angle+determined_angle
        modulo = (abs(x % (2*pi)) < 0.1) or (abs(x % (2*pi)-2*pi) < 0.1)
        self.assertEqual(modulo,True,msg="Angles applied %f and "
          "determined %f are different, difference %f" % (angle
                                                      ,determined_angle,x))
开发者ID:andreyto,项目名称:imp-fork-proddl,代码行数:28,代码来源:test_align2d.py

示例14: G

def G(x, k):
	result = []
	X = np.fft.fft(x, k)
	for i in range(len(X)):
		result.append(1/len(X) * (abs(X[i]) * abs(X[i])))

	return result
开发者ID:elvslv,项目名称:PatternRecognition,代码行数:7,代码来源:Labs4.py

示例15: has_split_dividents

def has_split_dividents(mdata, from_date, to_date):
    ''' Verifies if market data interval has splits, dividends '''
    from_diff = abs(mdata['close'][from_date] - mdata['adj_close'][from_date])
    to_diff = abs(mdata['close'][to_date] - mdata['adj_close'][to_date])
    if approx_equal(from_diff, to_diff, 0.0001):
        return False
    return not percent_equal(from_diff, to_diff, mdata['close'][to_date], 0.8)
开发者ID:dp0h,项目名称:candlesticks,代码行数:7,代码来源:mktdata.py


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