【问题标题】:diffrence between np.int16 and int16 matlab?np.int16 和 int16 matlab 之间的区别?
【发布时间】:2021-11-01 03:52:36
【问题描述】:

我正在将 matlab 代码转换为 Python。在matlab中有一行将复数转换为int16:

real = int16(real(-3.406578165491512e+04 + 9.054663292273188e+03i));
imag= int16(imag(-3.406578165491512e+04 + 9.054663292273188e+03i));  

real= -32768
imag=9055

在python中我试过这个:

real = np.int16(round(np.real(-3.406578165491512e+04 + 9.054663292273188e+03j)))
imag = np.int16(round(np.imag(-3.406578165491512e+04 + 9.054663292273188e+03j)))

real= 31470
imag=9055

结果不同(我有许多其他值,例如 (1.815808483565253e+04 + 3.533772674703890e+04j) 有不同的答案!)你能帮我得到相同的答案吗?

【问题讨论】:

    标签: python numpy matlab type-conversion complex-numbers


    【解决方案1】:

    MATLAB 输出已在 intmin('int16') = -32768 (docs) 处饱和,即它可以表示为 int16 变量的最大负值。

    Python 对 int16 (docs) 有相同的范围,但它没有在最大负值处饱和,而是遇到下溢,环绕到范围的顶部

    k = round(-3.406578165491512e+04) = -34066
    k = k + (32768*2) = 31470
    

    当输入仍然是浮点值时,您可以通过强制执行您首选的行为来解决此问题,然后当输入在-32768 to 32767 范围内时,您可以将其强制转换为int16

    【讨论】:

      【解决方案2】:

      Wolfie 发现了差异,这是关于如何解决它的问题。如果你对裁剪没问题,那么你可以使用iinfo 来获取整数类型的最小值和最大值(或者硬编码,如果你知道你永远不会从 int16 更改它)然后使用clip 在投射之前将浮动限制在这些范围内。

      n = -3.406578165491512e+04
      
      ii = np.iinfo(np.int16)
      print(f"min = {ii.min}") # min = -32768
      print(f"max = {ii.max}") # max = 32767
      
      np.int16(np.clip(n, ii.min, ii.max))
      # -32768
      

      重要提示:这仅在您的浮点数大于 int 的大小时才可靠,因为它依赖于能够将 ii.max 完全表示为浮点数。 See here for a discussion of when this is not true.

      这是一个失败的例子

      n = np.float64(1e100)
      
      ii = np.iinfo(np.int64)
      print(f"max: {ii.max}") # max = 9223372036854775807
      
      clipped = np.clip(n, ii.min, ii.max)
      print(f"clipped to: {int(clipped)}") # clipped to: 9223372036854775808
      print(f"as int: {np.int64(clipped)}") # as int: -9223372036854775808
      

      (发生这种情况是因为 ii.max 不能表示为浮点数。超过 9007199254740992,我们失去了 1 的精度位置,只能指定偶数,因此裁剪的边界变得不正确。)

      【讨论】:

        猜你喜欢
        • 2021-10-04
        • 2016-08-04
        • 2016-11-06
        • 1970-01-01
        • 2021-01-14
        • 2012-12-09
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多