在python中使用等式的错误答案

use*_*964 1 python math python-2.7

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

尝试使用python 2.7.x:

u = 4/3 * 6.67*1e-11*3.14*6378000*5515
print (u)  
Run Code Online (Sandbox Code Playgroud)

答案是7.36691253546

什么在这里不正确?

Mar*_*ers 6

整数除法.4/3向下舍入时评估为1.

4.0改用强制浮点运算:

>>> 4.0/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998
Run Code Online (Sandbox Code Playgroud)

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

Python 2.7.5 (default, May 22 2013, 12:00:45) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import division
>>> 4/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998
Run Code Online (Sandbox Code Playgroud)

二进制算术运算符部分中记录了此行为:

/(部门)和//(楼科)运营商获得他们的论据商.数字参数首先转换为通用类型.普通或长整数除法产生相同类型的整数; 结果是数学除法的结果,"floor"函数应用于结果.除以零会引发ZeroDivisionError异常.

请参阅PEP 238,了解为什么在Python 3中更改了此行为,以及对该from __future__ import division语句的引用.