问题:如何强制除法为浮点数?除数一直舍入到0?

我有两个整数值ab,但是我需要它们在浮点数中的比率。我知道a < b并且想要计算a / b,所以如果我使用整数除法,我将总是得到0,余数为a

c在下文中,如何在Python中强制成为浮点数?

c = a / b

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I’ll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python in the following?

c = a / b

回答 0

在Python 2中,两个整数的除法产生一个整数。在Python 3中,它产生一个浮点数。我们可以通过从中导入来获得新的行为__future__

>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.

>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

回答 1

您可以通过执行此操作来浮动c = a / float(b)。如果分子或分母是浮点数,则结果也将是。


一个警告:如评论员所指出的,如果b它不是整数或浮点数(或表示一个的字符串),则此方法将无效。如果您正在处理其他类型(例如复数),则需要检查这些类型或使用其他方法。

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won’t work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you’ll need to either check for those or use a different method.


回答 2

如何在Python中强制除法为浮点数?

我有两个整数值a和b,但是我需要它们在浮点数中的比率。我知道a <b并且我想计算a / b,所以如果我使用整数除法,我总是得到0并得到a的余数。

下面如何在Python中强制c为浮点数?

c = a / b

这里真正要问的是:

“我如何强制进行真正的除法以a / b返回分数?”

升级到Python 3

在Python 3中,要进行真正的除法,只需执行a / b

>>> 1/2
0.5

地板除法(整数的经典除法行为)现在为a // b

>>> 1//2
0
>>> 1//2.0
0.0

但是,您可能无法使用Python 2,或者编写的代码必须能同时在2和3中使用。

如果使用Python 2

在Python 2中,它不是那么简单。处理经典Python 2分区的某些方法比其他方法更好,更可靠。

对Python 2的建议

您可以在任何给定的模块中获得Python 3划分行为,并在顶部输入以下内容:

from __future__ import division

然后将Python 3样式划分应用于整个模块。它也可以在任何给定的点在python shell中工作。在Python 2中:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0

这确实是最好的解决方案,因为它可以确保模块中的代码与Python 3向前兼容。

Python 2的其他选项

如果您不想将其应用于整个模块,则只能使用一些解决方法。最受欢迎的是将其中一个操作数强制为浮点数。一种可靠的解决方案是a / (b * 1.0)。在新的Python Shell中:

>>> 1/(2 * 1.0)
0.5

truediv来自operator模块operator.truediv(a, b)的功能也很强大,但这可能会更慢,因为它是一个函数调用:

>>> from operator import truediv
>>> truediv(1, 2)
0.5

不建议用于Python 2

常见的是a / float(b)。如果b为复数,则将引发TypeError。由于定义了带有复数的除法,所以对我来说,在为除数传递一个复数时,除法不会失败。

>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

对我而言,故意使您的代码更脆弱没有太大意义。

您也可以使用-Qnew标记运行Python ,但这不利于执行具有新Python 3行为的所有模块,并且您的某些模块可能需要经典的划分,因此除测试外,我不建议这样做。但要演示:

$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j

How can I force division to be floating point in Python?

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I’ll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python in the following?

c = a / b

What is really being asked here is:

“How do I force true division such that a / b will return a fraction?”

Upgrade to Python 3

In Python 3, to get true division, you simply do a / b.

>>> 1/2
0.5

Floor division, the classic division behavior for integers, is now a // b:

>>> 1//2
0
>>> 1//2.0
0.0

However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.

If Using Python 2

In Python 2, it’s not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.

Recommendation for Python 2

You can get Python 3 division behavior in any given module with the following import at the top:

from __future__ import division

which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0

This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.

Other Options for Python 2

If you don’t want to apply this to the entire module, you’re limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:

>>> 1/(2 * 1.0)
0.5

Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it’s a function call:

>>> from operator import truediv
>>> truediv(1, 2)
0.5

Not Recommended for Python 2

Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.

>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

It doesn’t make much sense to me to purposefully make your code more brittle.

You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don’t recommend this except for testing. But to demonstrate:

$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j

回答 3

c = a / (b * 1.0)
c = a / (b * 1.0)

回答 4

在Python 3.x中,单斜杠(/)始终表示真实(非截断)除法。(//运算符用于截断除法。)在Python 2.x(2.2及更高版本)中,您可以通过将

from __future__ import division

在模块顶部。

In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a

from __future__ import division

at the top of your module.


回答 5

仅以浮点格式进行除法的任何参数也会产生浮点输出。

例:

>>> 4.0/3
1.3333333333333333

要么,

>>> 4 / 3.0
1.3333333333333333

要么,

>>> 4 / float(3)
1.3333333333333333

要么,

>>> float(4) / 3
1.3333333333333333

Just making any of the parameters for division in floating-point format also produces the output in floating-point.

Example:

>>> 4.0/3
1.3333333333333333

or,

>>> 4 / 3.0
1.3333333333333333

or,

>>> 4 / float(3)
1.3333333333333333

or,

>>> float(4) / 3
1.3333333333333333

回答 6

加一个点(.)表示浮点数

>>> 4/3.
1.3333333333333333

Add a dot (.) to indicate floating point numbers

>>> 4/3.
1.3333333333333333

回答 7

这也可以

>>> u=1./5
>>> print u
0.2

This will also work

>>> u=1./5
>>> print u
0.2

回答 8

如果要默认使用“ true”(浮点)除法,则有一个命令行标志:

python -Q new foo.py

有一些缺点(来自PEP):

有人认为,更改默认值的命令行选项是有害的。如果使用不当,肯定会很危险:例如,不可能将需要-Qnew的第三方库软件包与需要-Qold的第三方库软件包结合使用。

您可以通过查看python手册页了解有关更改/警告除法行为的其他标志值的更多信息。

有关除法更改的详细信息,请阅读:PEP 238-更改除法运算符

If you want to use “true” (floating point) division by default, there is a command line flag:

python -Q new foo.py

There are some drawbacks (from the PEP):

It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold.

You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.

For full details on division changes read: PEP 238 — Changing the Division Operator


回答 9

from operator import truediv

c = truediv(a, b)
from operator import truediv

c = truediv(a, b)

回答 10

from operator import truediv

c = truediv(a, b)

其中a是除数,b是除数。当两个整数相除后的商是浮点数时,此函数非常方便。

from operator import truediv

c = truediv(a, b)

where a is dividend and b is the divisor. This function is handy when quotient after division of two integers is a float.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。