Matlab numerictype/reinterpretcast equivalent in python?

后端 未结 2 1488
暖寄归人
暖寄归人 2021-01-18 00:07

In Matlab there is a command to define a new numeric type for example:

numerictype(0,16,8) 

see documentation: https://www.mathworks.com/help

相关标签:
2条回答
  • 2021-01-18 00:20

    You could use np.dtype. I used your representation of your dtype in the following snippet:

    import numpy as np
    dtype=[('signed', np.bool_), ('word', np.int16), ('frac', np.int16)] 
    mytype = np.dtype(dtype)
    

    and you can use it in an array like so:

    np.array([True,1,1],dtype=mytype)
    
    0 讨论(0)
  • 2021-01-18 00:30

    From a Python programmers perspective, getting really in the weeds with datatypes is antithetical to the nature of python itself. python is dynamically typed, which implies lack of efficiency, but ease of program-ability. To get around this, many popular libraries are written in c, so you may want to look to libraries like numpy to get your typing fix. Here is an example of setting datatypes in numpy. But to my knowledge, these only function on pre-defined c types

    theoretically, you might be able to define a special class to contain your data, implementing __add__, __subtract__, and whatever other key functions are necessary. However, as python is dynamically typed, this may have limited returns practically.

    One more option might be Cython, which allows you to define C types in python, but if you just want a quick function to define a type, the underlying nature of Python is fighting against you.

    0 讨论(0)
提交回复
热议问题