I was wondering what would be the efficient way to determine the value of a position on an array based on its nearest datapoint known value in Python?
Problem description:
There are datapoints in an array which are 1000 units apart and their values are known (see the figure). However, there are datapoints which fall between the known datapoints and their values should be determined based on their nearest known datapoint.
For instance, following the figure, the value of the datapoint at position 124200 should be set to 435 and the value of the datapoint at position 124850 should be set to 380.
At the moment, I am doing it like this:
# 'values' is an array which has the values for the known datapoints
# 'position' is an array that has the datapoints which their values should be determined
# 'step' keeps the number of units in between two datapoints with known values
# 'n' is a list which keeps the extracted values
for pos in positions:
if pos % step <= 500:
idx = (( pos - (pos % step)) / step) - 1
n.append(values[idx])
else: #pos % step > 500:
idx = (( pos + (step - (pos % step))) / step) - 1
n.append(values[idx])
I was also considering implementing the logic with addition and subtraction operations instead of modulo and division operations, but after some discussion with a friend, we came up with the conclusion that modern processors in doing divisions and multiplication are as fast as doing addition and subtraction, so I ruled that option out.