Skip to main content
 首页 » 编程设计

python之减去 float : 128. 0 和 int : 128 results in -5. 6834188608e-14

2025年05月04日14mayingbao

对 python 还是新手,所以这对我来说很奇怪......

def getNormalizedStart(self): 
        # center is Point: {X = 300, Y = 128} 
        center = self.getTargetCenterFromStart() 
 
        # effectiveStart is Point: {X=300.0,Y=472} 
        effectiveStart = self.getFirstActiveTouchEventLocations()[0]["Point"]\ 
            if self.isTouchTrial() else self.getFirstMouseEventLocation() 
 
        radians = float(MathUtils.angle(effectiveStart, center, True)) 
 
        # Point: {X=-44.0,Y=128.0} 
        newStart = MathUtils.rotatePoint(effectiveStart, center, -radians) 
 
        # newStart.X is float: -44 
        # center.X is int: 300 
        newStart.X -= center.X    # the result is -344. Good! 
 
        # newStart.Y is float: 128.0 
        # center.Y is int: 128 
        newStart.Y -= center.Y    # the result is -5.68434188608e-14. Wut? 
        return newStart 

但它在控制台中有效:

>>> x = 128.0 
>>> y = 128 
>>> x -= y 
>>> x 
0.0 

我是快疯了还是漏掉了一些明显的东西?

请您参考如下方法:

计算机中浮点运算的问题在于,通常您无法获得精确值。这是因为不可能用小数精确表示数字,128.0 - 128 等简单运算可能会导致非常小的错误。

像往常一样,必读的解释是What Every Computer Scientist Should Know About Floating-Point Arithmetic .