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

相关推荐
UIUV14 分钟前
JavaScript中this指向机制与异步回调解决方案详解
前端·javascript·代码规范
momo10014 分钟前
IndexedDB 实战:封装一个通用工具类,搞定所有本地存储需求
前端·javascript
liuniansilence14 分钟前
🚀 高并发场景下的救星:BullMQ如何实现智能流量削峰填谷
前端·分布式·消息队列
再花14 分钟前
在Angular中实现基于nz-calendar的日历甘特图
前端·angular.js
星辰烈龙16 分钟前
黑马程序员Java基础9
java·开发语言
San3021 分钟前
从零到一:彻底搞定面试高频算法——“列表转树”与“爬楼梯”全解析
javascript·算法·面试
GISer_Jing27 分钟前
今天看了京东零售JDS的保温直播,秋招,好像真的结束了,接下来就是论文+工作了!!!加油干论文,学&分享技术
前端·零售
Mapmost34 分钟前
【高斯泼溅】如何将“歪头”的3DGS模型精准“钉”在地图上,杜绝后续误差?
前端
@游子34 分钟前
Python类属性与魔术方法全解析
开发语言·python
JellyDDD36 分钟前
h5上传大文件可能会导致手机浏览器卡死,重新刷新的问题
javascript·上传文件