【问题标题】:Using decimals in math functions in python在 python 的数学函数中使用小数
【发布时间】:2022-10-23 15:01:28
【问题描述】:

那里! math 是一个 python 模块,许多人使用它来做一些更高级的数学函数 & 使用 decimal 模块,可以正确计算东西 1.2-1.1=0.0999~,但使用 decimal 类型它是 0.1

我的问题是这两个模块不能很好地相互配合。例如 log(1000, 10)=2.9999~ 但使用 decimal 类型会得到相同的结果。我怎样才能让这两者相互合作?我需要实现自己的功能吗?没有办法吗?

【问题讨论】:

  • 您能否将您的计算完全保留在decimal 模块环境中?例如。 decimal.Decimal(1000).log10() -> Decimal('3')

标签: python math decimal


【解决方案1】:

每个Decimal 实例都有Decimal.log10Decimal.lnDecimal.logb 方法,还有更多(maxsqrt):

from decimal import Decimal

print(Decimal('0.001').log10())
# Decimal('-3')
print(Decimal('0.001').ln())
# Decimal('-6.907755278982137052053974364')

但是,没有三角函数。

任意精度计算的更高级替代方案是 mpmath,可在 PyPI 上获得。当然,它也不会为您提供sintan,因为sin(x) 对于许多x 值是不合理的,因此将其存储为Decimal 没有意义。但是,给定固定精度,您可以通过 Tailor 系列等在 mpmath 帮助下计算这些函数。您也可以使用Decimal(math.sin(0.17)) 来获得一些小数,该值接近于 0.17 弧度的正弦值。

另请参阅official Decimal recipes

【讨论】:

    【解决方案2】:

    Decimal 中有一个 log10 方法。

    from decimal import *
    a = Decimal('1000')
    print(a.log10())
    

    但是,如果您尝试使用精确整数解法求解对数,则使用计算对数精确值的函数对我来说更有意义。对数函数在典型使用中通常会输出一些不合理的结果。您可以改为使用 for 循环和重复除法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2017-01-05
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      相关资源
      最近更新 更多