简体   繁体   English

没有科学计数法的Python计算

[英]Python calculations without scientific notation

I have tried to use python to work with some big numbers, which hard to calculate manually. 我尝试使用python处理一些较大的数字,这些数字很难手动计算。 Let's say I have 2 in power of 256 as a long integer as a starting point. 假设我有2的幂数256作为一个长整数作为起点。 Then, when I want to do anything with it like divide by 2, python gives me value with scientific notation like this 5.78960446186581e+76 . 然后,当我想对它做任何事情(例如,除以2)时,python用5.78960446186581e+76这样的科学符号为我提供了价值。

However, I need very precise numbers where everything makes a difference. 但是,我需要非常精确的数字,所有这些都可以有所作为。 How can I get rid of this scientific notation, when I'm doing calculations? 在进行计算时,如何摆脱这种科学计数法?

You should use the integer division in Python 3, eg: 您应该在Python 3中使用整数除法,例如:

a = 2 ** 256
print(a / 2)
print(a // 2)

This will print 这将打印

5.78960446186581e+76
57896044618658097711785492504343953926634992332820282019728792003956564819968

You can use the decimal module from the standard library: 您可以使用标准库中的decimal模块:

import decimal

if __name__ == '__main__':
    decimal.getcontext().prec = 100
    a = decimal.Decimal(1) / decimal.Decimal(7)
    b = decimal.Decimal(str(a * decimal.Decimal(str(1e100))))
    print(a)
    print(b)

output: 输出:

0.1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571429 1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571429

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM