简体   繁体   English

我正在学习Python,为什么在此示例中使用浮点数?

[英]I'm learning Python and why is a floating-point used in this example?

http://learnpythonthehardway.org/book/ex4.html http://learnpythonthehardway.org/book/ex4.html

There's an extra credit question asking me to explain why the floating-point 4.0 is used instead of 4. 还有一个额外的信用问题,要求我解释为什么使用浮点4.0而不是4。

I understand that a floating point is used for accuracy, but I can't fathom why it is necessary in any case in this example. 我知道使用浮点数是为了提高准确性,但是我无法理解为什么在此示例中无论如何都需要使用浮点数。

There doesn't actually seem to be any need for a float instead of an int in that particular example. 在该特定示例中,似乎实际上不需要任何浮点数而不是int数。 It could have an effect if you were to divide something by it, but that's not happening here. 如果您将某事除以某事可能会产生影响,但这不是在这里发生。 (And even then, it'd depend on whether you were using Python 2 or 3, as float division is the default in 3). (即使那样,这仍取决于您使用的是Python 2还是3,因为float拆分是3中的默认设置)。

If you look at the comments below, zedshaw (the author) admits as much: 如果您查看下面的评论,则zedshaw(作者)也承认:

Михаил Груздев: And why 4.0 used for space? МихаилГруздев:为什么将4.0用于空间? Maybe it's drivers variable value should be floating-point? 也许它的驱动程序变量值应该是浮点数?

zedshaw: Simply to introduce floating point as a little puzzle. zedshaw:简单介绍一下浮点数是一个小难题。 Mathematically the exercise doesn't make much sense, it's just practice. 从数学上讲,练习没有多大意义,而只是练习。 Continue on for now. 现在继续。

A floating point is used because in Python an int divided by an int produces an int ( integer division ) which is not intended here. 使用浮点是因为在Python中,将int除以int会产生一个int整数除法 ),此处不打算使用int If you divide a float by an int or an int by a float , you get a float . 如果将float除以int或将int除以float ,则会得到一个float

Example: 例:

   4/3
=> 1
   4.0/3
=> 1.3333333333333333
   2*4/3
=> 2
   2*4.0/3
=> 2.6666666666666665

This is because of something called Integer Division. 这是因为有一个叫做“整数除法”的东西。 Basically this means that if you divide two integers, the resulting number must be an integer. 基本上,这意味着如果将两个整数相除,则结果数必须是整数。 So, for example 3/4 would result in 0 and 4/3 would result in 1 . 因此,例如3/4将导致04/3将导致1 This is because 3/4 in "real" math would give you 0.75 and to turn 0.75 into and integer, Python truncates the floating point values and leaves you with 0. 这是因为“实际”数学中的3/4会给您0.75,然后将0.75转换为整数,Python会截断浮点值并使您剩下0。

The easiest way to fix this is to use 4.0 instead of 4. Turning the integer into a float and disregarding Integer Division because integer divided by float results in a float. 解决此问题的最简单方法是使用4.0而不是4。将整数转换为浮点数,而忽略整数除法,因为整数除以浮点数会导致浮点数。 3/4.0 equals 0.75 like you want it to. 3/4.0等于0.75

Arithmetic with integer operands has an integer result. 具有整数操作数的算术运算结果为整数。

>>> 3 / 2
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM