python - 在 Python 中计算小数的幂

标签 python

我想用 Python 计算 Decimal 的幂,例如:

from decimal import Decimal
Decimal.power(2,2)

上面应该返回我作为 Decimal('2)

如何计算小数的幂?

编辑: 这是我做的

y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))

x,deci_x是小数类型

但上面的表达式抛出错误:

decimal.InvalidOperation: x ** (non-integer)

堆栈跟踪:

Traceback (most recent call last):
  File "ha.py", line 28, in ?
    first_k_1=first_k(2,n-1,k)
  File "ha.py", line 18, in first_k
    y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))
  File "/usr/lib64/python2.4/decimal.py", line 1709, in __pow__
    return context._raise_error(InvalidOperation, 'x ** (non-integer)')
  File "/usr/lib64/python2.4/decimal.py", line 2267, in _raise_error
    raise error, explanation

最佳答案

您可以使用 ** 计算功率:

2**3  # yields 8

a = Decimal(2)
a**2  # yields Decimal(4)

根据您的更新,我觉得还可以:

>>> x = Decimal(2)
>>> deci_x = Decimal(1)
>>> n=4
>>> y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))
>>> y
Decimal('10000')

关于python - 在 Python 中计算小数的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567720/

相关文章:

javascript - 向 Flask render_template 端点发出客户端 POST 请求

python - 最大每月值,同时保留该值发生时的数据

python - pandas 使用 .loc 对多列进行条件赋值

python 3.3 : LAN speed test which calculates the read & write speeds and then returns the figure to Excel

python - 无法安装 pip centos 6.7

python - C/C++ 中的 DNS 解析

python - 最大化 vim 的快速修复窗口?

python - celery 不适用于全局变量

python - 使用 re.split 拆分字符串时的额外空元素

python - 让 namedtuple 接受 kwargs