Hia, for various purposes I’ve created an Interpolation Set class. A picture explains better than words, so let met start with that:
http://cal007300.student.utwente.nl/vincent/Interpolation.jpg
The Interpolation set contains a series of key/value floats. What I want to be able to do is to query the set for any key-value in the interpolation and get a corresponding result. So, in the example above, the data set contains the following key-value pairs:
[tr]
[td]Key[/td]
[td]Value[/td]
[/tr]
[tr]
[td]0[/td]
[td]160[/td]
[/tr]
[tr]
[td]0.4[/td]
[td]160[/td]
[/tr]
[tr]
[td]0.625[/td]
[td]98[/td]
[/tr]
[tr]
[td]1.0[/td]
[td]55[/td]
[/tr]
When I query this set for key-value 0.5, I want the set to return the interpolated value.
- In this case, 0.5 is in between keys 0.4 and 0.625. To calculate the interpolated value
- First I determine the distance between the keys. The distance between the keys in the set is (0.625-0.4) = 0.225.
- The distance between the queried key and the lowest-nearest key (the first key to the left of the queried key…) is 0.5 - 0.4 = 0.1.
- 0.1 is 44.44% (0.1 / 0.255) of the way of the distance between the two known keys.
- So finally we have to calculate what 44.44% of the way of the distance between the values is. The distance between the values is 98-160 = -62
- … 44% of -62 = -27.55.
- The final value and the value I wanted to get from the set is the leftmost value (160) plus the interpolated value (-27.55) so finally : 160 + -27.55 = 132.45.
Now the question for this forum is: what would be an (the most?) optimized way of approaching this problem? attached to this message is one way of doing this. But I have the gut feeling that it can be done in a better way.
When quering for a key lower than the lowest key in the set, the set should just return the first value. In case you query for a key higher than the highest key in the set, just return the last value.