简体   繁体   中英

convert string to float16 in python

I am currently using numpy (I don't know how to make a datatype float16 in python otherwise) as this:

a = np.string_('1.234').astype(np.float16)

then:

type(a)
numpy.float16

Is ther another option? Is it better?

It would be great if you could explain what am I doing when converting the python string into numpy string!

Thank you!

You can go directly from python string to np.float16 :

import numpy as np

f16 = np.float16("1.234")
print(type(f16))

f16 = np.float16(1.234)  # works as well

Output:

<class 'numpy.float16'>

Reference: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.inexact

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