python - 如何限制 numpy 浮点计算精度
问题描述
我正在使用 numpy 来计算相机图像,这将由无符号整数灰度值表示。我想限制浮点精度,以加快计算速度。例如,假设我正在计算由高斯光束的强度分布形成的图像:
import numpy as np
import matplotlib.pyplot as plt
nx = 1000
ny = 1000
px = 5e-3
x = np.linspace(0, nx * px)
y = np.linspace(0, ny * px)
X, Y = np.meshgrid(x, y)
xc = x[-1] / 2
yc = y[-1] / 2
sigma = 1
gauss_profile = np.exp(-(np.square(X - xc) + np.square(Y - yc)) / sigma**2)
print(gauss_profile.dtype)
bitdepth = 12
gauss_profile *= 2**bitdepth - 1
camera_image = gauss_profile.astype(np.uint16)
#%% plot image
fig = plt.figure()
ax = fig.add_subplot(111)
grey_cmap = plt.get_cmap('gray')
im = ax.imshow(camera_image,
cmap=grey_cmap,
extent=(0, nx * px,
0, ny * px))
plt.xlabel('x (mm)')
plt.ylabel('y (mm)')
plt.colorbar(im)
有没有办法让 gauss_profile 不使用 float64 精度计算,而是使用足以获得所需灰度值的最小分辨率?到目前为止,我尝试在之前初始化数组并将其传递给out
np.exp 调用中的关键字,但这会导致 TypeError 或 ValueError 取决于 dtype。有没有其他方法可以加速这个计算?
解决方案
也许尝试设置您的 ndarraysx
并y
使用dtype np.half或np.single。这将限制浮点精度。但我不知道计算是否仍在发生。
np.half:半精度浮点数类型。(float16)
np.single:单精度浮点数类型,兼容C float.(float32)
x = np.linspace(0, nx * px, dtype=np.half)
y = np.linspace(0, ny * px, dtype=np.half)
...
推荐阅读
- ios - 标签栏在 iOS11 iPad 上未使用全宽
- javascript - 单击两个按钮时如何更改图像?
- r - 比较列表的元素并应用条件
- oracle - 'tmpdata' 和 'Get_Parameter_List' 如何在 OracleForm 中工作?
- javascript - 在源代码中将 JSON 数据重新定义为 JavaScript 对象是否有好处?
- swift - 如何快速在 UIView 上应用带有边框的尖角半径?
- tensorflow - 您必须为占位符张量“x”提供一个值
- multidimensional-array - F# - 将锯齿状数组转换为 Array2D
- java - 使用 @SuppressWarnings("unchecked") 时的性能注意事项
- linux - 在ps中隐藏命令执行检测