Skip to content

Instantly share code, notes, and snippets.

@Xainey
Last active May 24, 2016 19:56
Show Gist options
  • Save Xainey/fa5677b6c2d500e0366654128e022e88 to your computer and use it in GitHub Desktop.
Save Xainey/fa5677b6c2d500e0366654128e022e88 to your computer and use it in GitHub Desktop.
Lagrange Interpolation in Powershell
<#
Lagrange Interpolation Example
#>
function Point($x, $y)
{
return [pscustomobject]@{
PSTypeName = 'Point'
x = $x
y = $y
}
}
function Find-InterpolatedValue
{
param
(
[parameter(Mandatory=$true)]
[array]
$Points,
[parameter(Mandatory=$true)]
[double]
$FindAt,
[parameter(Mandatory=$false)]
[array]
$Range = (0, $Points.Length)
)
# Expand Points to array
$x = $Points | select -ExpandProperty x
$y = $Points | select -ExpandProperty y
# Get Points in range
$_x = $x[$Range[0]..$Range[1]]
$_fx = $y[$Range[0]..$Range[1]]
$n = $_x.Length
$interpolatedValue = 0
for ($i = 0; $i -lt $n; $i++)
{
$lagrangian = 1.0
for ($j = 0; $j -lt $n; $j++)
{
if ($j -ne $i)
{
$lagrangian *= ($FindAt - $_x[$j]) / ($_x[$i] - $_x[$j]);
}
}
$interpolatedValue += $lagrangian * $_fx[$i];
}
return $interpolatedValue
}
cls
$points = @(
Point 0.3 0.404958
Point 0.5 0.824361
Point 0.7 1.40963
Point 0.9 2.21364
Point 1.1 3.30458
)
$at = 0.6
Find-InterpolatedValue -Points $points -Range (0,2) -FindAt $at
Find-InterpolatedValue -Points $points -Range (0,3) -FindAt $at
Find-InterpolatedValue -Points $points -Range (1,4) -FindAt $at
Find-InterpolatedValue -Points $points -Range (0,4) -FindAt $at
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment