V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SystemLight
V2EX  ›  Python

Python 中的 numpy 定义 dtype 为 short 以后为什么赋值 32768 的值是-32768 ?

  •  
  •   SystemLight ·
    SystemLight · 2020-05-04 18:28:49 +08:00 · 2418 次点击
    这是一个创建于 1445 天前的主题,其中的信息可能已经有所发展或是发生改变。

    a = np.array([1, 2, 3, 4, 5, 6, 32768]) a.dtype = np.short print(a)

    输出: [ 1 0 2 0 3 0 4 0 5 0 6 0 -32768 0]

    输出的结果为什么分成了两个值了呢?

    7 条回复    2020-05-05 15:49:44 +08:00
    minami
        1
    minami  
       2020-05-04 18:33:34 +08:00 via Android
    呃,这是被转型了吧,没发现数组长度都不对了吗?你要初始化时就指定 dtype,不要这样强转
    junkun
        2
    junkun  
       2020-05-04 18:50:46 +08:00
    short 补码的表示范围就是-32768~32767,没办法表示 32768 。
    SystemLight
        3
    SystemLight  
    OP
       2020-05-04 19:08:56 +08:00
    @junkun 是的是的,明白了

    @minami 还真是,感谢启发,我输出值以后从 np.short 类型转成了 python int 类型,所以最高位变了,符号位置也就变了

    python_val = -32769

    print(bin(python_val)) # 符号位+中间数字+已有的 16 位数字位 -0b1000000000000001 存成补码 1...1...0111111111111111

    print(python_val)

    numpy_short_val = np.short(python_val) # numpy 得到以后把只取 16 位,发现最高位是 0 为正数,正数原码=补码 0111111111111111

    print(bin(numpy_short_val)) # 当 python 再读取出来时:0111111111111111 就是 32767

    print(numpy_short_val)
    byaiu
        4
    byaiu  
       2020-05-04 19:12:09 +08:00 via Android
    其实 dtype 是可以强转的,在数据很大的时候是很有必要的。
    SystemLight
        5
    SystemLight  
    OP
       2020-05-04 19:17:12 +08:00
    @byaiu 但是我这样转换,数组大小却变了
    byaiu
        6
    byaiu  
       2020-05-05 07:59:05 +08:00 via Android
    @SystemLight 说明原始的类型不是 short 而是 int 。
    我以前是有处理十多个 G 数据的需求,数据可以直接用 np.fromfile 从文件里直接获取,同时要指定 dtype 。然后改变 dtype 来按照不同的格式观察同一数据。
    enrio
        7
    enrio  
       2020-05-05 15:49:44 +08:00
    钓,就硬钓。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3905 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 04:13 · PVG 12:13 · LAX 21:13 · JFK 00:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.