python - python 中方程式的错误答案

标签 python math python-2.7

试试 Wolphram Alpha - 这是正确的结果。

用 python 2.7.x 试试:

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

答案是 7.36691253546

这里哪里不对?

最佳答案

整数除法。 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 中实现同样的效果:

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

此行为记录在 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关于为什么在 Python 3 中改变了这种行为,以及对 from __future__ import division 语句的引用。

关于python - python 中方程式的错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232328/

相关文章:

Python 守护线程和 "with"语句

python - 从一个字符串中添加 2 个字典条目

python - 钢铁 worker 工作完成通知

python - 在 Python-RQ 中减少机器上的 worker 数量?

python - 为什么通过 Homebrew 安装的 Python 不包括 Tkinter

haskell - 类型的标识是什么?

javascript - 如何利用JS计算用户输入的数字的中位数

algorithm - 如何在 3D 网格中线性迭代?

python - 从列表中生成多个条件语句

python - 使用 ConfigParser 创建一个包含文件中指定的所有元素的类