【发布时间】:2021-06-25 06:35:22
【问题描述】:
如何处理 mysql 数据类型的 python 和 django 模型中的大量数字?
我想存储大的十进制数字,例如太阳的质量,以 kg 为单位
(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。 -
@WillemVanOnsem
max_digits和decimal_places对于像9.961558465069068e-35这样的巨大数字,我使用什么?因为我必须将它放入 mysql 数据库中。 -
在这种情况下,您将需要
max_digits=51和decimal_places=51之类的东西。因此,这将表示0和1之间的值,“分辨率”为10e-51。 -
@WillemVanOnsem 为什么是 51?你是怎么到 51 岁的?
-
因为您的号码有 16 位数字,并且位于逗号后面的 35 位数字,所以 16+35=51。
标签: python mysql django django-models floating-point