首页 > 代码库 > LU分解,Javascript代码

LU分解,Javascript代码

///A 为矩阵,这里写成一维数组,如 【1】,【1,2,3,4】function GetLU(a){	var n = a.length;//矩阵的总数据数目	var s = Math.sqrt(n);//矩阵的阶数	var L = new Array(n);	var U = new Array(n);	if (GetDet(a) != 0){	var allOrderNotEqulesZero = true;	for (var i = 0; i < s; i++)	{		if (GetDet(GetOrderMatrix(a, i)) == 0)		{			allOrderNotEqulesZero  = false;			break;		}	}		        if (allOrderNotEqulesZero){	for (var i = 0; i < s; i++)	{		for (var j = 0; j < s; j++)		{			if (i == j)			{				L[i*s + j] = 1;			}			else if (i < j)			{			     L[i*s+j] = 0;			}	            		if (i > j)                		U[i*s+j] = 0;		            U[0*s+j] = a[0*s+j];            		L[i*s+0] = a[i*s+0] / U[0*s+0];		}	}	 for (var k = 1; k < s; k++)    	{        for (var j = k; j < s; j++)        {            tmp = 0;            for (var m = 0; m < k; m++)            {                tmp += L[k*s+m] * U[m*s+j];            }            U[k*s+j] = a[k*s+j] - tmp;        }        for (var i = k+1; i < s; i++)        {            tmp = 0;            for (var m = 0; m < k; m++)            {                tmp += L[i*s+m] * U[m*s+k];            }            L[i*s+k] = ( a[i*s+k] - tmp ) / U[k*s+k];        }    }}else {	alert(‘该矩阵的顺序主子式中有零!‘)	console.log(GetLastMatrix(a));	for (var i = 0; i < s; i++)	{		for (var j = 0; j < s; j++)		{			if (j > i)			{				U[i * s + j] = a[i * s + j];				L[i * s + j] = 0;			}else if (j == i){	U[i * s + j] = a[i * s + j];				L[i * s + j] = 1;}else{	L[i * s + j] = a[i * s + j];				U[i * s + j] = 0;}		}	}}	console.log(L);	console.log(U);}else{	alert(‘该矩阵为奇异矩阵,无法进行LU分解!‘);}		}function GetDet(a){	var n = a.length;//矩阵的总数据数目	var s = Math.sqrt(n);//矩阵的阶数	var sum = 0;	if (n == 1)	{		return a[0];	}	for (var i = 0; i < s; i++)	{		if (i % 2 == 0)		{			sum += a[i] * GetDet(GetSubMatrix(a, i))		}		else		{			sum -= a[i] * GetDet(GetSubMatrix(a, i))		}	}	return sum;}///获取比较第n列之后的矩阵function GetLastMatrix(a){	var n = a.length;//矩阵的总数据数目	var s = Math.sqrt(n);//矩阵的阶数	var p = [];	for (var i = 0; i < s; i++)	{		for (var j = 0; j < s; j++)		{			if (i == j)			{				p.push(1);			}			else {				p.push(0);			}		}	}	for (var i = 0; i < s -1; i++)	{		a = GetNewMatrix(a, i, p); 	}	console.log(p);	return a;}function GetNewMatrix(a, k, p){	var n = a.length;//矩阵的总数据数目	var s = Math.sqrt(n);//矩阵的阶数	var result = [];	var maxRowNum = 0;	var MAXValue = http://www.mamicode.com/Math.abs(a[ k * s + k]);>

  

LU分解,Javascript代码