Last active
September 9, 2019 15:58
-
-
Save kaipyroami/deee4c765dcd81c0fed25fe7a7a5d719 to your computer and use it in GitHub Desktop.
This is a simple example of a 2 dimensional lookup table with linear interpolation in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
var yi1, yi2, xi1, xi2 int // Lookup table indexes around point | |
var x, y float64 // x,y axis values at indexes | |
var y1, y2, x1, x2 float64 // Axis values of indexes | |
var q11, q12, q21, q22 float64 // xy, lookup values at indexes | |
xAxis := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} | |
yAxis := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} | |
lookup := [][]float64{ | |
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, | |
{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, | |
{2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10}, | |
{3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10}, | |
{4, 4, 4, 4, 4, 5, 6, 7, 8, 9, 10}, | |
{5, 5, 5, 5, 5, 5, 6, 7, 8, 9, 10}, | |
{6, 6, 6, 6, 6, 6, 6, 7, 8, 9, 10}, | |
{7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 10}, | |
{8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 10}, | |
{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10}, | |
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, | |
} | |
// Input values | |
x = 3.45 | |
y = 5.78 | |
for i, v := range xAxis { | |
if v >= x { | |
x1, x2 = xAxis[i-1], xAxis[i] | |
xi1, xi2 = i-1, i | |
break | |
} | |
} | |
for i, v := range yAxis { | |
if v >= y { | |
y1, y2 = yAxis[i-1], xAxis[i] | |
yi1, yi2 = i-1, i | |
break | |
} | |
} | |
q11 = lookup[xi1][yi1] | |
q12 = lookup[xi1][yi2] | |
q21 = lookup[xi2][yi1] | |
q22 = lookup[xi2][yi2] | |
d := (x2 - x1) * (y2 - y1) | |
t1 := (((x2 - x) * (y2 - y)) / d) * q11 | |
t2 := (((x - x1) * (y2 - y)) / d) * q21 | |
t3 := (((x2 - x) * (y - y1)) / d) * q12 | |
t4 := (((x - x1) * (y - y1)) / d) * q22 | |
val := t1 + t2 + t3 + t4 | |
fmt.Println("Between x:", x1, x2) | |
fmt.Println("Between y:", y1, y2) | |
fmt.Println("Calculated:", val) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment