如何处理 python 中的大数字,mysql 的 django 模型?
How to handle large numbers in python, django models for mysql?
如何处理 python 和 mysql 数据类型的 django 模型中的大数?
我想存储大的十进制数,例如以千克为单位的太阳质量
(1.98847±0.00007)×10^30 kg
以及其他大量物理学和天文学。
我需要什么max_digits
和decimal_places
?
对于简单的经度,纬度我使用11,6:
models.DecimalField(max_digits=11, decimal_places=6, null=False)
>>> s = 1.9884723476542349808764
>>> s
1.988472347654235
>>>
>>> c = 9.961558465069068e-35
>>> c
9.961558465069068e-35
>>> Decimal(c)
Decimal('9.9615584650690682798407470173147606387909020112701851758062095613274216457861081111717165524621631078616701415739953517913818359375E-35')
>>>
您应该使用 Decimal
[python-doc],而不是 float
:
from decimal import Decimal
s = <b>Decimal(</b>'1.9884723476542349808764'<b>)</b>
例如:
>>> Decimal('1.9884723476542349808764')
Decimal('1.9884723476542349808764')
>>> Decimal('1.9884723476542349808764') * 3
Decimal('5.9654170429627049426292')
A Decimal
是一种可以任意精度工作的数字类型。如果您使用 DecimalField
,那么这也会提供 Decimal
值。但是,如果您将 float
写入 DecimalField
,则可能会出现舍入错误,因为 float
.
的尾数有限
如何处理 python 和 mysql 数据类型的 django 模型中的大数?
我想存储大的十进制数,例如以千克为单位的太阳质量
(1.98847±0.00007)×10^30 kg
以及其他大量物理学和天文学。
我需要什么max_digits
和decimal_places
?
对于简单的经度,纬度我使用11,6:
models.DecimalField(max_digits=11, decimal_places=6, null=False)
>>> s = 1.9884723476542349808764
>>> s
1.988472347654235
>>>
>>> c = 9.961558465069068e-35
>>> c
9.961558465069068e-35
>>> Decimal(c)
Decimal('9.9615584650690682798407470173147606387909020112701851758062095613274216457861081111717165524621631078616701415739953517913818359375E-35')
>>>
您应该使用 Decimal
[python-doc],而不是 float
:
from decimal import Decimal
s = <b>Decimal(</b>'1.9884723476542349808764'<b>)</b>
例如:
>>> Decimal('1.9884723476542349808764')
Decimal('1.9884723476542349808764')
>>> Decimal('1.9884723476542349808764') * 3
Decimal('5.9654170429627049426292')
A Decimal
是一种可以任意精度工作的数字类型。如果您使用 DecimalField
,那么这也会提供 Decimal
值。但是,如果您将 float
写入 DecimalField
,则可能会出现舍入错误,因为 float
.