简体   繁体   中英

Python calculations without scientific notation

I have tried to use python to work with some big numbers, which hard to calculate manually. Let's say I have 2 in power of 256 as a long integer as a starting point. 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 .

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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