gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:52 26 4
gpt4 key购买 nike

对 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 .

关于python - 减去 float : 128. 0 和 int : 128 results in -5. 6834188608e-14?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15714644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com