在Python中存储超过9000位的大数字 [英] Storing big numbers over 9,000 digits in Python

查看:64
本文介绍了在Python中存储超过9000位的大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算在Python中使用很大的数字,但想知道Python是否可以处理很大的数字.这些数字将最多包含3,000个零.

I'm planning to use very big numbers in Python, but wonder if Python can handle very big numbers. The numbers are going to have up to 3,000 zeros.

而且,具有1个3,000个零的字节使用了多少字节?

And, how much bytes does a 1 with 3,000 zeros use?

第三个问题,如何在不使用str()的情况下使用Python将数字保存为整数到文件中?

Third question, how can I save a number as integer into a file with Python without having to str() it?

推荐答案

Python可以使用 long 类型存储任意长整数,甚至可以通过附加来指定 long 文字对他们来说是 L (例如, 0L long 零,而不是 0 > int ).更好的是,当计算结果太大而无法用 int int s提升为 long s>. long 是完整的数字类型,并且与所有Python数字操作兼容.

Python can store arbitrarily long integers using the long type and even lets you specify long literals by appending an L to them (e.g. 0L is a long zero, as opposed to just 0 which is an int). Even better, it automatically "promotes" numbers from ints to longs when the result of a calculation is too large to be represented by an int. long is a full-fledged numeric type and is compatible with all Python numeric operations.

如果需要多个整数,则需要 decimal 模块,该模块具有 Decimal 类型,该类型提供任意大小和精度的实数,而没有固有的问题二进制浮点表示形式.

If you need more than integers, then you want the decimal module, which features a Decimal type that provides real numbers of arbitrary size and precision, without the issues inherent to binary floating-point representations.

long 和 Decimal 的缺点是它们分别比 int float 慢,因为后者具有本机硬件支持.但是对大量数字进行数学运算会有点慢,根本无法使用这些数字.

The downside of both long and Decimal is that they are slower than int and float, respectively, because the latter have native hardware support. But doing math on large numbers somewhat slowly beats not being able to use such numbers at all.

关于大小, int 对象在32位Python中为12个字节.内部看似32位元的数字看似很大,这是由于Python的一切都是对象"方法.(我相信,但请不要引用我,该值有4个字节,从实例到类型的指针有4个字节,而引用计数器有4个字节,用于确定对象何时可以被垃圾回收.-collected.这些字段在64位版本的Python上可能更大.)

As for size, int objects are 12 bytes in 32-bit Python. This seemingly large size for what is internally a 32-bit quantity is due to Python's "everything's an object" approach. (I believe, but don't quote me, that there's 4 bytes for the value, 4 bytes for a pointer from the instance to the type, and 4 bytes for a reference counter, which is used to determine when an object can be garbage-collected. These fields may be larger on 64-bit versions of Python.)

long 的大小因数字(加上对象开销)而异,但是任何 long 值的大小都可以使用 sys.getsizeof().

The size of a long varies, as they vary based on the number (plus object overhead), but the size of any long value can be determined using sys.getsizeof().

这篇关于在Python中存储超过9000位的大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆