How to limit numpy float computation precision

Viewed 204

I am using numpy to calculate camera images, which would be represented by unsigned integer grayvalues. I would like to limit the floating point accuracy, in order to speed up the computation. So as an example, say I'm calculating the image formed by the intensity distribution of a gaussian beam:

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)

Is there any way to have gauss_profile not be calculated with float64 precision, but rather a minimum resolution which is enough to get the desired gray value? So far, I tried initializing the array before and passing it to the out keyword in the np.exp call, but this resulted in a TypeError or ValueError depending on the dtype. Is there any other way to accelerate this computation?

1 Answers

Maybe try setting your ndarrays x and y with dtype np.half or np.single. This will limit the float precision. But I don't know if the computation is still happening though.

np.half: Half-precision floating-point number type. (float16)

np.single: Single-precision floating-point number type, compatible with C float.(float32)

x = np.linspace(0, nx * px, dtype=np.half)
y = np.linspace(0, ny * px, dtype=np.half)

...
Related