Cramer‘s Rule

cramer.js

javascript 复制代码
function Cramer2(vec2x2A, vec2B) {
	this.A = vec2x2A;
	this.B = vec2B;
}
Cramer2.det2 = function(v) {
	return v[0][0] * v[1][1] - v[0][1] * v[1][0];
};
Cramer2.xCol = function(vec2x2A, B, col) {
	var nVec = [];
	var i, j;
	for (i = 0; i < 2; i++) {
		nVec[i] = [];
		for (j = 0; j < 2; j++) {
			if (j == col) {
				nVec[i].push(B[i]);
			} else {
				nVec[i].push(vec2x2A[i][j]);
			}
		}
	}
	return nVec;
}
Cramer2.prototype.getX = function() {
	var D, Dx, Dy;
	
	D = Cramer2.det2(this.A);
	Dx = Cramer2.det2( Cramer2.xCol(this.A, this.B, 0) );
	Dy = Cramer2.det2( Cramer2.xCol(this.A, this.B, 1) );
	
	return [Dx/D, Dy/D];
}


function Cramer3(vec3x3A, vec3B) {
	this.A = vec3x3A;
	this.B = vec3B;
}

Cramer3.det3 = function(v) {
	return v[0][0] * (v[1][1]*v[2][2] - v[2][1]*v[1][2]) - 
			v[0][1] * (v[1][0]*v[2][2] - v[2][0]*v[1][2]) +
			v[0][2] * (v[1][0]*v[2][1] - v[2][0]*v[1][1]);
};

Cramer3.xCol = function(v3x3, B, col) {
	var nVec = [];
	var i, j;
	for (i = 0; i < 3; i++) {
		nVec[i] = [];
		for (j = 0; j < 3; j++) {
			if (j == col) {
				nVec[i].push(B[i]);
			} else {
				nVec[i].push(v3x3[i][j]);
			}
		}
	}
	return nVec;
}

Cramer3.prototype.getX = function() {
	var D, Dx, Dy, Dz;
	
	D = Cramer3.det3(this.A);
	Dx = Cramer3.det3( Cramer3.xCol(this.A, this.B, 0) );
	Dy = Cramer3.det3( Cramer3.xCol(this.A, this.B, 1) );
	Dz = Cramer3.det3( Cramer3.xCol(this.A, this.B, 2) );
	
	return [Dx/D, Dy/D, Dz/D];
}

module.exports = {
	Cramer2: Cramer2,
	Cramer3: Cramer3
};

* index.js

javascript 复制代码
var cramer = require("./cramer");

/* 2x-y=1 and x-3y=8 */
var A = [[2,-1],[1,-3]], B = [1, 8];
var cramer2 = new cramer.Cramer2(A, B);
console.log(cramer2.getX());

/* x+y+z=2, 2x + y + 3z = 9, and x - 3y + z = 10 */
A = [ [1,1,1], [2,1,3], [1,-3,1] ];
B = [2, 9, 10];
var cramer3 = new cramer.Cramer3(A, B);
console.log(cramer3.getX()); /* [1,-2,3] */

Cramer's Rule

相关推荐
拾光拾趣录几秒前
从“祖传”构造函数到 `class`
前端·javascript
wmm_会飞的@鱼4 分钟前
FlexSim-汽车零部件仓库布局优化与仿真
服务器·前端·网络·数据库·数学建模·汽车
yvvvy7 分钟前
从“按钮都不会点”到“能撸大厂 UI”:我用 react-vant 踢开组件库的大门!
前端·javascript
安然dn8 分钟前
Cropper.js:JS图像裁剪库
前端·javascript
Serendipity2619 分钟前
微服务架构
前端·微服务
Hilaku25 分钟前
深入background-image:你可能不知道的几个性能优化与高级技巧
前端·css
南岸月明27 分钟前
副业自媒体1年终于明白:为什么会表达的人,能量越来越强,更能赚到钱?
前端
Danny_FD41 分钟前
Vue + Element UI 实现模糊搜索自动补全
前端·javascript
gnip1 小时前
闭包实现一个简单Vue3的状态管理
前端·javascript
斐济岛上有一只斐济1 小时前
后端程序员的CSS复习
前端