Javascript中的递归插值
我正在开发一个浏览器游戏,其中包括许多维度的立方插值。我需要获取一组值和一组坐标,并输出nD空间中该点的估计值。我发现了一些很棒的1D三次插值教程,以及一些C++中的ND三次插值的例子(两者)。问题是这个C++代码使用了很多指针和位移位器,这两个JS都没有。p> 1D三次插值很长,但对任何感兴趣的人来说都是这样的: f(a,b,c,d,x)=b+0.5*x*(c-a+x*(2*a-5*b+4*c-d+x*(3*(b-c)+d-a)),其中a-d是已知值,x是0到1之间的值,用于确定b和c之间的点的相对位置 Js: 二维插值可以简单地如下实现: g(a1、b1、c1、d1、a2、b2、c2、d2、a3、b3、c3、d3、a4、b4、c4、d4、x、y)= f(f(a1,b1,c1,d1,y),f(a2,b2,c2,d2,y),f(a3,b3,c3,d3,y),f(a4,b4,c4,d4,y),x) Js: 3d也是这样:Javascript中的递归插值,javascript,arrays,interpolation,Javascript,Arrays,Interpolation,我正在开发一个浏览器游戏,其中包括许多维度的立方插值。我需要获取一组值和一组坐标,并输出nD空间中该点的估计值。我发现了一些很棒的1D三次插值教程,以及一些C++中的ND三次插值的例子(两者)。问题是这个C++代码使用了很多指针和位移位器,这两个JS都没有。p> 1D三次插值很长,但对任何感兴趣的人来说都是这样的: f(a,b,c,d,x)=b+0.5*x*(c-a+x*(2*a-5*b+4*c-d+x*(3*(b-c)+d-a)),其中a-d是已知值,x是0到1之间的值,用于确定b和c之间的点
function interpolate3d(arr, x, y, z){
let a = [
interpolate2d(arr[0], y, z),
interpolate2d(arr[1], y, z),
interpolate2d(arr[2], y, z),
interpolate2d(arr[3], y, z)
];
return interpolate(a, x);
}
我是Js的新手,(刚从C++和java来的),不知道很多额外的特性。我没有找到任何在线的东西,除了<代码>数组.ReleEo()/<代码>(不知道如何使用嵌套数组)和上面链接的递归C++代码:
double nCubicInterpolate (int n, double* p, double coordinates[]) {
assert(n > 0);
if (n == 1) {
return cubicInterpolate(p, *coordinates);
}
else {
double arr[4];
int skip = 1 << (n - 1) * 2;
arr[0] = nCubicInterpolate(n - 1, p, coordinates + 1);
arr[1] = nCubicInterpolate(n - 1, p + skip, coordinates + 1);
arr[2] = nCubicInterpolate(n - 1, p + 2*skip, coordinates + 1);
arr[3] = nCubicInterpolate(n - 1, p + 3*skip, coordinates + 1);
return cubicInterpolate(arr, *coordinates);
}
}
double-nCubicInterpolate(int n,double*p,double坐标[]){
断言(n>0);
如果(n==1){
返回立方极(p,*坐标);
}
否则{
双arr[4];
int skip=1到JavaScript的翻译可以是:
function nCubicInterpolate(p, coordinates) {
if (coordinates.length == 1) {
return cubicInterpolate(p, coordinates[0]);
} else {
let fewerCoordinates = coordinates.slice(1);
let arr = p.map(hyperplane => nCubicInterpolate(hyperplane, fewerCoordinates));
return cubicInterpolate(arr, coordinates[0]);
}
}
请注意,JavaScript中不需要参数n
,因为坐标
数组参数的长度对应于它。而且p
的嵌套级别应该是相同的n
。JavaScript没有编译时类型检查,因此liberty在这里发挥了优势:没有指针;p
一个数组,但它可以是一个数字数组,或一个数字数组,或…等等
完整地说,cubicInterpolate
功能如您在问题中所述:
function cubicInterpolate(p, x) {
return p[1] + 0.5 * x*(p[2] - p[0] + x*(2*p[0] - 5*p[1] + 4*p[2] - p[3] + x*(3*(p[1] - p[2]) + p[3] - p[0])));
}
nCubicInterpolate的第6行不应该是返回cubicInterpolate(arr,坐标[0]);
而不是返回cubicInterpolate(arr,坐标);
?好的,只是想确定一下。
function nCubicInterpolate(p, coordinates) {
if (coordinates.length == 1) {
return cubicInterpolate(p, coordinates[0]);
} else {
let fewerCoordinates = coordinates.slice(1);
let arr = p.map(hyperplane => nCubicInterpolate(hyperplane, fewerCoordinates));
return cubicInterpolate(arr, coordinates[0]);
}
}
function cubicInterpolate(p, x) {
return p[1] + 0.5 * x*(p[2] - p[0] + x*(2*p[0] - 5*p[1] + 4*p[2] - p[3] + x*(3*(p[1] - p[2]) + p[3] - p[0])));
}