I have a problem discretizing in python.
I have a list st
:
st=[(-0.8,0.8),(-0.5,0.5),(-0.104,0.104),(-0.872,0.872)]
I would like to discretize 'st' into a number of parts determined by a different list. In other words, I would like to divide each element of the list into n
parts.
For example, I would like to divide by the elements of the list b=(3,3,6,2)
. Therefore (-0.8,0.8)
will be divided into 3 parts. (-0.5,0.5)
would be split into 3 parts and so on.
The output should look like st=[[(-0.8,-0.2),(-0.2,0.2),(0.2,0.8)),....]] thank you.
I think there are two issues that can be dealt with separately:
For that, let us look at a simpler example:
import numpy as np
a = (-0.8,0.8)
b = 3
c = np.linspace(a[0], a[1], b + 1)
d = list(zip(c, c[1:]))
print(d)
Which outputs:
[
(-0.80000000000000004, -0.26666666666666672),
(-0.26666666666666672, 0.26666666666666661),
(0.26666666666666661, 0.80000000000000004)
]
st=[(-0.8,0.8),(-0.5,0.5),(-0.104,0.104),(-0.872,0.872)]
b=(3,3,6,2)
result = []
for start_stop, parts in zip(st, b):
start, stop = start_stop
c = np.linspace(start, stop, parts + 1)
d = list(zip(c, c[1:]))
result.append(d)
print(result)
Which results in:
[
[
(-0.80000000000000004, -0.26666666666666672),
(-0.26666666666666672, 0.26666666666666661),
(0.26666666666666661, 0.80000000000000004)
],
[
(-0.5, -0.16666666666666669),
(-0.16666666666666669, 0.16666666666666663),
(0.16666666666666663, 0.5)
],
and so on...
Zip matches elements from one list to another and lets you loop over them together so that's very useful here.
NumPy's Linear Spacing function (np.linspace) is the operation you want to perform. See details here