HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Determining the value of a position on an array based on its nearest datapoint known value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningthearraynearestpositionvalueitsknownbaseddatapoint

Problem

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 + (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.

Solution

This is an application of rounding.

idx = int(round(float(pos) / step)) - 1


Note, however, that the result in case pos is exactly halfway into a step is different from your code, and also differs between Python versions.

Code Snippets

idx = int(round(float(pos) / step)) - 1

Context

StackExchange Code Review Q#63662, answer score: 2

Revisions (0)

No revisions yet.