Public Group

#### Archived

This topic is now archived and is closed to further replies.

# How do you do interpolation?

This topic is 5464 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

What I want to do is be able to do linear interpolation. Something like this:
function do_linear_interpolation (key)
{
int keys   = {0,   1,   2,   3}
int values = {0, 100, 200, 300}

if (key > 3) return values[2]
if (key < 0) return values[0]

int interpolatedValue = 0

/* i don''t know what goes here */

return interpolatedValue
}

int v = do_linear_interpolation(2.51)
/* i want v to contain 251 */

Just a simple example, but how do I do it?

##### Share on other sites
This is how I'd do it:

Figure out which numbers it's between, then figure out the values of both. Subtract the first number from the second.

So for 2 and 3 you have 200 and 300. The difference is 100.

Then treat your decimal as a percent, multiply it by the distance, and add it to the value of the first number.

So, .51 * 100 = 51.

Then: 51+200 = 251.

I think I have a function that does this, let me check...

Edit: Check this out...I think it works.
float GetAvgVal(float pos1, float pos2, float middlepos, float pos1val, float pos2val) {float percent = (middlepos - pos1)/(pos2 - pos1);return (1-percent)*pos1val + (percent)*pos2val;}

pos 1 and 2 would be your key 1 and 2.
middlepos would be the key you want interpolated.
pos1val and pos2 val would be the key 1 and 2 values.

If this doesn't work, feel free to bitch at me. I wrote it for a heightmap thing I can't get working yet because of DirectX stuff.

-=Lohrno

[edited by - Lohrno on November 7, 2003 7:44:26 PM]

##### Share on other sites
Thanx!!! I have a good feeling on how it works just looking by looking at your explanation.

1. 1
Rutin
46
2. 2
3. 3
4. 4
5. 5
JoeJ
19

• 11
• 15
• 9
• 10
• 13
• ### Forum Statistics

• Total Topics
633004
• Total Posts
3009836
• ### Who's Online (See full list)

There are no registered users currently online

×