代码之家  ›  专栏  ›  技术社区  ›  MehdiB

这个条件在python脚本中意味着什么

  •  -1
  • MehdiB  · 技术社区  · 6 年前

    我试图把Python脚本翻译成Java。因为我对Python不太熟悉,所以我无法理解这个脚本中的条件。这是原稿:

    import numpy as np
    def inverse_generalized_anscombe(x, mu, sigma, gain=1.0):        
    
        test = np.maximum(x, 1.0)
        exact_inverse = ( np.power(test/2.0, 2.0) +
                          1.0/4.0 * np.sqrt(3.0/2.0)*np.power(test, -1.0) -
                          11.0/8.0 * np.power(test, -2.0) +
                          5.0/8.0 * np.sqrt(3.0/2.0) * np.power(test, -3.0) -
                          1.0/8.0 - np.power(sigma, 2) )
        exact_inverse = np.maximum(0.0, exact_inverse)
        exact_inverse *= gain
        exact_inverse += mu
        exact_inverse[np.where(exact_inverse != exact_inverse)] = 0.0
        return exact_inverse
    

    我不明白的是这句话:

    exact_inverse[np.where(exact_inverse != exact_inverse)] = 0.0
    

    正如我所理解的,精确的反方向应该是一个单值,而不是一个数组,那么为什么前面有一对方括号呢?方括号中的条件是什么? exact_inverse != exact_inverse 情况似乎总是 false 或者我在这里错过了什么。

    可以找到原始脚本 here

    1 回复  |  直到 6 年前
        1
  •  2
  •   ForceBru    6 年前

    首先, (numpy.nan != numpy.nan) is True 所以, exact_inverse != exact_inverse 总是错误的。

    接下来,考虑一下:

    >>> exact_inverse = 5
    >>> exact_inverse += numpy.array([1,2]) # this may be 'mu', the same for 'gain'
    >>> exact_inverse
    array([6, 7]) # no longer an integer
    

    此外,如果 x 是一个数组,然后:

    >>> x = numpy.array([1,2,3])
    >>> numpy.maximum(x, 1.0)
    array([ 1.,  2.,  3.]) # that's an array!
    

    然后,对数组和数字进行除法、乘法、加法等运算,得到元素操作。