2016-11-15 64 views
0

我在Matlab拉格朗日插值代碼:拉格朗日插值在JavaScript

function[r] = interpolation(x, y) 
    r = 0; 
    for i = 1:size(x,2) 
    w = 1; 
    for j = 1:size(x,2) 
     if j ~= i 
     w = conv(w, [1, -x(j)])/(x(i) - x(j)); 
     end 
    end 
    r = r + y(i) * w; 
    end 
end 

,但我需要在JavaScript這個插值代碼。有人能幫我嗎?

回答

1

function interpolation(x, y) { 
 
    // x, y :: number[] (same size) 
 

 
    // result = 0 
 
    var result = []; 
 
    for (var k = 0; k < x.length; k++) { 
 
    result[k] = 0; 
 
    } 
 

 
    for (var i = 0; i < x.length; i++) { 
 

 
    var basis = [1]; 
 
    for (var j = 0; j < x.length; j++) { 
 

 
     if (i != j) { 
 
     if (x[i] == x[j]) { 
 
      throw new Error("All x-values must be distinct"); 
 
     } 
 

 
     // basis = conv(basis, [1, -x[j]])/(x[i] - x[j]) 
 
     basis = conv(basis, [1, -x[j]]).map(function(z) { 
 
      return z/(x[i] - x[j]); 
 
     }); 
 

 
     } 
 
    } 
 

 
    // result += y[i] * basis 
 
    result = result.map(function(r, k) { 
 
     return r + y[i] * basis[k]; 
 
    }); 
 

 
    } 
 
    return result; 
 
} 
 

 
function conv(x, y) { 
 
    // x, y :: number[] 
 

 
    var result = []; 
 
    for (var k = 0; k < x.length + y.length - 1; k++) { 
 

 
    var sum = 0; 
 
    for (var i = 0; i < x.length; i++) { 
 
     var j = k - i; 
 

 
     if (j >= 0 && j < y.length) { 
 
     sum += x[i] * y[j]; 
 
     } 
 
    } 
 

 
    result[k] = sum; 
 
    } 
 

 
    return result; 
 
} 
 

 
console.log('interpolation([1, 2, 3], [1, 4, 9]) =', 
 
      interpolation([1, 2, 3], [1, 4, 9])); 
 

 
console.log('interpolation([1, 2, 3], [1, 8, 27]) =', 
 
      interpolation([1, 2, 3], [1, 8, 27]));