在 python 中将字符串转换为 float16
convert string to float16 in python
我目前正在使用 numpy(否则我不知道如何在 python 中创建数据类型 float16),如下所示:
a = np.string_('1.234').astype(np.float16)
然后:
type(a)
numpy.float16
还有别的选择吗?好点了吗?
如果你能解释一下我在将 python 字符串转换为 numpy 字符串时做了什么,那就太好了!
谢谢!
您可以直接从 python 字符串转到 np.float16
:
import numpy as np
f16 = np.float16("1.234")
print(type(f16))
f16 = np.float16(1.234) # works as well
输出:
<class 'numpy.float16'>
参考:https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.inexact
我目前正在使用 numpy(否则我不知道如何在 python 中创建数据类型 float16),如下所示:
a = np.string_('1.234').astype(np.float16)
然后:
type(a)
numpy.float16
还有别的选择吗?好点了吗?
如果你能解释一下我在将 python 字符串转换为 numpy 字符串时做了什么,那就太好了!
谢谢!
您可以直接从 python 字符串转到 np.float16
:
import numpy as np
f16 = np.float16("1.234")
print(type(f16))
f16 = np.float16(1.234) # works as well
输出:
<class 'numpy.float16'>
参考:https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.inexact