Charles L.
Charles L.

Reputation: 6275

hard code exact float values in python

This is probably overkill for my problem, but I am curious about the answer.

I have a matrix of np.float32 values that I want to put into some code. It's 50x3 so I want to just put it in the source directly - it's not something that will change often. It's a little sensitive to rounding, so I want to encode the data exactly if possible. Is there a good way to do this in the source while also preserving the matrix format?

I'm thinking something along the lines of putting [[0xC45B36F3, ...],...] and somehow encoding that to a np.float32.

Upvotes: 1

Views: 275

Answers (3)

B. M.
B. M.

Reputation: 18628

You can convert the matrix m in bytes :

m.tobytes()  

Then you paste the bytes it in your code :

data=b'\x34f\xd3.......paste the 4*50*3 bytes here ......\x12'

After you can reconstruct the exact matrix :

m=matrix(frombuffer(data,float32).reshape(50,3)) 

without any loss.

Upvotes: 1

Eric
Eric

Reputation: 97571

If you chose to encode the integer values, you could then do:

int_data = np.array([[0xC45B36F3, ...],...], dtype=np.uint32)
floats = int_data.view(np.float32)

Upvotes: 2

MSeifert
MSeifert

Reputation: 152637

Why don't you use the numpy.save builtin? I've tried it with several float32 inputs and the numpy.load had no rounding issues.

Or is there any reason why you can't or don't want to do it that way?

Upvotes: 2

Related Questions