I need to fill an array with the position of the boundary of n_cells
(starting from 0 up to n_cells 1
) with the size of the cell in geometric progression (with parameter c
) and the total size will be thick (thus x[0]=0
and x[n_cells]=thick
)
I have this which works:
n_cells=10
c=0.9
thick=2
x = np.zeros(n_cells 1)
x_0=thick * (c - 1) / (c**n_cells - 1)
for i in range(n_cells):
x[i 1] = x[i] x_0 * c ** i
Since I'm learning, is there a simpler pythonic comprehension way to do the same?
CodePudding user response:
You could try to use the numba.njit
module. It will speed up your code. It is not more pythonic but it will be faster if you use a larger n_cells
.
See the example below
import numpy as np
from numda import njit
@njit
def fast_goem():
n_cells=10
c=0.9
thick=2
x = np.zeros(n_cells 1)
x_0=thick * (c - 1) / (c**n_cells - 1)
for i in range(n_cells):
x[i 1] = x[i] x_0 * c ** i
return x
CodePudding user response:
Ok I found a way by using numpy stuff:
x_0=thick * (c - 1) / (c**n_cells - 1)
x=np.cumsum(np.concatenate(([0],np.geomspace(x_0, x_0*c**(n_cells-1), num=n_cells))))
however readability is not improved (I don't like the concatenate) so I wouldn't mark this answer as more "pythonic" just shorter