Reputation: 21
try it with Wolphram Alpha - this is correct result.
try it with python 2.7.x:
u = 4/3 * 6.67*1e-11*3.14*6378000*5515
print (u)
Answer would be 7.36691253546
What is here incorrect?
Upvotes: 1
Views: 872
Reputation: 1121216
Integer division. 4/3
evaluates to 1 as it is rounded down.
Use 4.0
instead to force floating point arithmetic:
>>> 4.0/3 * 6.67*1e-11*3.14*6378000*5515
9.822550047279998
or use Python 3, where floating point division is the default, or use from __future__ import division
to achieve the same in 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
This behaviour is documented under the 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 theZeroDivisionError
exception.
See PEP 238 about why this behaviour was changed in Python 3, and for a reference to the from __future__ import division
statement.
Upvotes: 6
Reputation: 133504
The problem is the integer division 4/3
in Python 2.7
>>> print (4.0/3) * 6.67*1e-11*3.14*6378000*5515
9.82255004728
In Python 3 (where /
is float division and //
is integer division) This would have worked without changing it to 4.0/3
, alternatively you may use
from __future__ import division
Upvotes: 3