本文介绍了为什么1 // 0.1 == 9.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在Python 2.7 和 3.x 中,为什么整数除法给我一个不正确的数字由数字 0 ? 负数 -1 甚至可以正常工作: >>> 1 //。1 9.0 >>> 1 // - 。1 -10.0 据我所知,或正数)向负无穷大转,然而我会认为 1 //。1 会导致 10.0 1 可以被除以 .1 而不剩余。 解决方案您在这里看到的实质上是使用 / 的正常划分和 // 。 还有一点很重要,就是,这是一个不确定的,只是因为它们是如何工作的。在这种情况下,最好使用 decimal 模块来检查实际发生了什么。所以,让我们看看你在这里做什么: 首先, .1 已经不精确了: >>>十进制(.1)十进制('0.1000000000000000055511151231257827021181583404541015625') 所以,让我们来看看实际结果如下: >>>十进制(1)/十进制(.1)十进制('9.999999999999999444888487687')>>> 1 / .1 10.0 正如您所看到的,使用 / 并不完全给你带有浮点运算的 10 。但是非常接近这就是为什么当你使用正常的花车时,你实际上会返回10(因为在不精确的数字类型中分割不准确会立即丢失)。 ,结果是在之前纠正了不精确性,所以这就是为什么你得到 9 : >>>十进制(1)//十进制(.1)十进制('9')>>> 1 / .1 10.0 对于负数,地板效应是相反的,正如在另一个问题中所解释的那样: >>>十进制(1)/十进制( - 。1)十进制(' - 9.999999999999999444888487687')>>> 1 / -.1 -10.0 >>>十进制(1)//十进制( - 。1)十进制(' - 9')>>> 1 // -.1 -10.0 In Python 2.7 and 3.x, why does integer division give me a non-correct number when dividing by a number 0 < x < 1?Negative numbers -1 < x < 0 even work correctly:>>> 1//.19.0>>> 1//-.1-10.0I understand that integer division with a negative (or positive) number rounds toward negative infinity, however I would have thought 1//.1 should result in 10.0 since 1 can be divided by .1 without remainder. 解决方案 What you’re seeing here is essentially the effect of the difference between "normal" division using / and flooring division with //.What’s also always important to keep in mind is the general issue with floating point arithmetic which is a certain imprecision just because of how they work. In those situations, it’s always good to use the decimal module to check what’s actually going on. So let’s look at what you are doing here:First of all, .1 is already not precise:>>> Decimal(.1)Decimal('0.1000000000000000055511151231257827021181583404541015625')So, let’s look at the actual result of the divisions:>>> Decimal(1) / Decimal(.1)Decimal('9.999999999999999444888487687')>>> 1 / .110.0As you can see, the normal division using / does not exactly give you 10 with floating point arithmetic. But it’s really close. That’s why, when you use normal floats, you actually get back 10 (since the division imprecision is immediately lost in the imprecision of the number type).When using flooring division, the result is floored before the imprecision is corrected, so that’s why you get 9:>>> Decimal(1) // Decimal(.1)Decimal('9')>>> 1 / .110.0With negative numbers, the flooring effect is the opposite direction, as explained in that other question:>>> Decimal(1) / Decimal(-.1)Decimal('-9.999999999999999444888487687')>>> 1 / -.1-10.0>>> Decimal(1) // Decimal(-.1)Decimal('-9')>>> 1 // -.1-10.0 这篇关于为什么1 // 0.1 == 9.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 08:45