用python中的等式回答错误

2024-04-24 03:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用Wolphram Alpha-这是正确的结果。在

在python 2.7.x中尝试:

u = 4/3 * 6.67*1e-11*3.14*6378000*5515
print (u)  

答案是7.36691253546

这里有什么不正确的?在


Tags: 答案alphaprintwolphram
2条回答

问题在于Python2.7中的整数除法4/3

>>> print (4.0/3) * 6.67*1e-11*3.14*6378000*5515
9.82255004728

在Python3中(其中/是浮点除法,//是整数除法),这在不将其更改为4.0/3的情况下就可以工作了,或者您可以使用

^{pr2}$

整数除法。4/3向下取整时求值为1。在

请改用4.0强制浮点运算:

>>> 4.0/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998

或者使用Python 3,其中浮点除法是默认值,或者使用from __future__ import division在Python 2中实现相同的效果:

^{pr2}$

此行为记录在Binary arithmetic operators section下:

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception.

请参见PEP 238,了解为什么在python3中更改了此行为,以及对from __future__ import division语句的引用。在

相关问题 更多 >