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

相关推荐
草莓熊Lotso2 分钟前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
小妖6663 分钟前
html 滚动条滚动过快会留下边框线
前端·html
heroboyluck17 分钟前
Svelte 核心语法详解:Vue/React 开发者如何快速上手?
前端·svelte
海的诗篇_19 分钟前
前端开发面试题总结-JavaScript篇(二)
开发语言·前端·javascript·typescript
琹箐29 分钟前
ant-design4.xx实现数字输入框; 某些输入法数字需要连续输入两次才显示
前端·javascript·anti-design-vue
程序员-小李30 分钟前
VuePress完美整合Toast消息提示
前端·javascript·vue.js
cccc来财44 分钟前
Go中的协程并发和并发panic处理
开发语言·后端·golang
狐凄1 小时前
Python实例题:Python计算线性代数
开发语言·python·线性代数
Uyker1 小时前
从零开始制作小程序简单概述
前端·微信小程序·小程序
惊鸿一博1 小时前
java_网络服务相关_gateway_nacos_feign区别联系
java·开发语言·gateway