Path: blob/trunk/third_party/closure/goog/math/tdma.js
2868 views
// Copyright 2011 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview The Tridiagonal matrix algorithm solver solves a special16* version of a sparse linear system Ax = b where A is tridiagonal.17*18* See http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm19*20*/2122goog.provide('goog.math.tdma');232425/**26* Solves a linear system where the matrix is square tri-diagonal. That is,27* given a system of equations:28*29* A * result = vecRight,30*31* this class computes result = inv(A) * vecRight, where A has the special form32* of a tri-diagonal matrix:33*34* |dia(0) sup(0) 0 0 ... 0|35* |sub(0) dia(1) sup(1) 0 ... 0|36* A =| ... |37* |0 ... 0 sub(n-2) dia(n-1) sup(n-1)|38* |0 ... 0 0 sub(n-1) dia(n)|39*40* @param {!Array<number>} subDiag The sub diagonal of the matrix.41* @param {!Array<number>} mainDiag The main diagonal of the matrix.42* @param {!Array<number>} supDiag The super diagonal of the matrix.43* @param {!Array<number>} vecRight The right vector of the system44* of equations.45* @param {Array<number>=} opt_result The optional array to store the result.46* @return {!Array<number>} The vector that is the solution to the system.47*/48goog.math.tdma.solve = function(49subDiag, mainDiag, supDiag, vecRight, opt_result) {50// Make a local copy of the main diagonal and the right vector.51mainDiag = mainDiag.slice();52vecRight = vecRight.slice();5354// The dimension of the matrix.55var nDim = mainDiag.length;5657// Construct a modified linear system of equations with the same solution58// as the input one.59for (var i = 1; i < nDim; ++i) {60var m = subDiag[i - 1] / mainDiag[i - 1];61mainDiag[i] = mainDiag[i] - m * supDiag[i - 1];62vecRight[i] = vecRight[i] - m * vecRight[i - 1];63}6465// Solve the new system of equations by simple back-substitution.66var result = opt_result || new Array(vecRight.length);67result[nDim - 1] = vecRight[nDim - 1] / mainDiag[nDim - 1];68for (i = nDim - 2; i >= 0; --i) {69result[i] = (vecRight[i] - supDiag[i] * result[i + 1]) / mainDiag[i];70}71return result;72};737475