Python大浮动师

时间:2013-04-15 11:22:57

标签: python floating-point

我尝试使用浮点数在Python中进行除法但是我得到的结果不正确,即使我尝试舍入浮点数但它没有用。有没有其他wat如何python为大浮点数划分?

>>> div = 1.45751734864e+15/30933
>>> print div
47118525478.9

在java中相同

>>> double div = 1.45751734864e+15/30933;
>>> System.out.println(div);
4.711852547893835E10

3 个答案:

答案 0 :(得分:1)

您可以使用十进制模块来提高精度。

>>> from decimal import *
>>> getcontext().prec = 30
>>> Decimal(1.45751734864e+15) / Decimal(30933)
Decimal('47118525478.9383506287783273527')

阅读:http://docs.python.org/2/tutorial/floatingpoint.htmlhttp://docs.python.org/2/library/decimal.html

答案 1 :(得分:1)

Python和Java结果都正确

Python

47118525478.9

<强>爪哇

4.711852547893835E10

但是,在Java中,数字以exponential notation格式打印。所以,它相当于:

  

4.711852547893835 * 10 ^ 10 = 47118525478.9835

如果您想以指数表示法格式打印Python的输出,请使用String format

>>> div = 1.45751734864e+15/30933
>>> print '{:e}'.format(float(div))
4.711853e+10

答案 2 :(得分:0)

Python和Java返回的数字是相同的:

使用python 2.7.3的IPython:

In [1]: 1.45751734864e+15/30933
Out[1]: 47118525478.93835

In [2]: 1.45751734864e+15/30933.0
Out[2]: 47118525478.93835

In [3]: 1.45751734864e+15/30933.0-4.711852547893835E10
Out[3]: 0.0

Python 3.3:

Python 3.3.0 (default, Mar 22 2013, 20:14:41) 
[GCC 4.2.1 Compatible FreeBSD Clang 3.1 ((branches/release_31 156863))] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.
>>> 1.45751734864e+15/30933
47118525478.93835
>>> 1.45751734864e+15/30933-4.711852547893835E10
0.0
>>> 
相关问题