【问题标题】:How to handle large numbers in python, django models for mysql?如何处理python中的大量数字,mysql的django模型?
【发布时间】:2021-06-25 06:35:22
【问题描述】:

如何处理 mysql 数据类型的 python 和 django 模型中的大量数字? 我想存储大的十进制数字,例如太阳的质量,以 kg 为单位 (1.98847±0.00007)×10^30 kg 和其他大量的物理学和天文学。

我需要什么max_digitsdecimal_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_digitsdecimal_places 对于像 9.961558465069068e-35 这样的巨大数字,我使用什么?因为我必须将它放入 mysql 数据库中。
  • 在这种情况下,您将需要max_digits=51decimal_places=51 之类的东西。因此,这将表示01 之间的值,“分辨率”为10e-51
  • @WillemVanOnsem 为什么是 51?你是怎么到 51 岁的?
  • 因为您的号码有 16 位数字,并且位于逗号后面的 35 位数字,所以 16+35=51。

标签: python mysql django django-models floating-point


【解决方案1】:

您应该使用Decimal [python-doc],而不是float

from decimal import Decimal

s = Decimal('1.9884723476542349808764')

例如:

>>> Decimal('1.9884723476542349808764')
Decimal('1.9884723476542349808764')
>>> Decimal('1.9884723476542349808764') * 3
Decimal('5.9654170429627049426292')

Decimal 是一种可以以任意精度工作的数字类型。如果您使用DecimalField,那么这也将提供Decimal 值。但是,如果您将float 写入该DecimalField,则由于float 的尾数有限,可能会出现舍入错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多