2

I need to create a square-shaped grid with both x and y axes having the following parameters:

min_range = 0
max_range = 0.8
cell_size = 0.01

And what I do:

import numpy as np
x_ax = np.arange(min_range, max_range, cell_size) ### This gives [0,...,0.1,...,0.29,0.79]
y_ax = np.arange(min_range, max_range, cell_size) ### This also gives [0,...,0.1,...,0.29,0.79]
### Cartesian product
lattice = np.transpose([np.tile(x_ax, y_ax.shape[0]), np.repeat(y_ax, x_ax.shape[0])])

Then, lattice matrix is passed as an argument to another function and a value is assigned to each of its cells. I need to visualize this grid with the assigned values stored in a separate array. So what I do is:

lattice = np.asarray(lattice/cell_size,dtype=np.int32) ###This is supposed to contain matrix indices.

And this is where I get strange results. Some of the values in the lattice matrix, for example 0.29 when divided by 0.01 which is the cell_size give 28. I cannot figure out where this problem is coming from as it happens only for a few of the values in the intended range. I suspected it was the rounding issue with the floating point numbers as mentioned here and tried it with np.linspace as well. But that did not help either.

How can I make this visualization work correctly?

EdgeRover
  • 195
  • 1
  • 15

1 Answers1

2

In the Python console you will see

>>> 0.29/0.01
28.999999999999996
>>> import numpy as np
>>> np.int32(0.29/0.01)
28

So you are on the right path. This is due to floating point calculation. As soon as you cast it to np.int32, the decimal places will be truncated and the result is 28. Instead of just casting, you should round the result:

>>> np.int32(np.round(0.29/0.01))
29

For your application that means you have to write

lattice = np.asarray(np.round(lattice/cell_size),dtype=np.int32) ###This is supposed to contain matrix indices.
koalo
  • 2,113
  • 20
  • 31