【问题标题】:Raise Integers to negative integer powers in Python 2.7在 Python 2.7 中将整数提高到负整数幂
【发布时间】:2020-06-22 17:37:36
【问题描述】:

我很难将这个 Matlab 代码翻译成 Python。

我会向你展示我到目前为止的努力。

这是matlab代码

Sigma=BW1/(2*(2*(-log(10^(att_bw/10)))^(1/Order))^(1/2))

现在我尝试使用今天早上早些时候学习的 Python 幂运算符 **

我的代码是

BW1 = np.array([100])
att_bw = np.array([-3])
Order = np.array([1])
Sigma = BW1/(2*(2*(-np.log(10**(att_bw[0]/10)))**(1/Order))**(1/2))

但不幸的是它说它无法处理负面权力

sigma 的结果应该是42.539

编辑:看来我的代码在 Python 3 中运行得非常好。但是我坚持使用 Python 2.7。那么有什么简单的移植方法吗?

【问题讨论】:

  • @TedLyngmo BW 而不是 BW1 这是一个错字。我有负能量。 att_bw 为 -3
  • 可能也值得利用一些数学恒等式;例如np.log(10**x)np.log(10)*x 但不会溢出或溢出
  • @TedLyngmo 您能否在此处添加答案作为评论?我将不胜感激
  • 我不明白我的代码是如何为你工作的。我得到 ValueError: Integers tonegative integer powers are not allowed。因为在某一时刻,我向 att_btw[0] 提出了一些问题,即 -3 和一个负数,这反过来又导致程序失败
  • 我使用的是 Python 2.7.18。会不会是这个原因?

标签: python python-2.7 numpy


【解决方案1】:

在 python2 中,您需要确保使用浮点数。为此,请在公式中的每个整数后添加 .

像这样:

import numpy as np

BW1 = np.array([100])
att_bw = np.array([-3])
Order = np.array([1])
Sigma = BW1/(2.*(2.*(-np.log(10.**(att_bw[0]/10.)))**(1./Order))**(1./2.))
print Sigma

输出

[42.53892736]

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 2016-03-28
    • 1970-01-01
    • 2018-07-12
    • 2012-09-15
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多