简体   繁体   中英

Convert double number to float number

I need to do some elaborations on MATLAB data in Python. The data is stored as an array of doubles in Matlab. When I retrieve it, despite being stated here that double data types from Matlab are converted in float data types when handled by Python, I get this error:

TypeError: unorderable types: double() < float()

What I'm trying to do is this

import matlab.engine

eng=matlab.engine.connect_matlab()

x = eng.workspace['MyData']
x = x[len(x)-1]
if x < 0.01:
    #do stuff

How can I convert the double number stored in the array to a float so that I can use it alongside my other Python variables?

Converting doubles into floats in Matlab is as simple as calling the single function :

A = rand(10);
whos A;

B = single(A);
whos B;

As per console output:

  Name       Size            Bytes  Class     Attributes

  A         10x10              800  double              

  Name       Size            Bytes  Class     Attributes

  B         10x10              400  single 

Be careful about the loss of precision, since you are converting 64 bit numeric values into 32 bit numeric values.

EDIT

Since you can't manipulate your Matlab data, in order to accomplish this I suggest you to use either Numpy (refer to this function in case: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.astype.html ) or struct for a straight conversion (refer to this answer in case: convert double to float in Python ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM