本文主要是介绍js 解二元一次方程组(消元法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解二元一次方程,首先想到的就是消元法
确定好消元法,就按照消元法制定算法
二元一次方程 结构为
ax + by = c
kx + fy = s
x和y为变量,a、b、c、k、f、s、为常量
1.确定常量,用户 输入|定义 常量
let a = 2,b = 3,c = 13,k = 3,f = 4,s = 18
2.取 a和k(或者 b和f)的最大公约数,消掉 x (或者y),这举出 a和k 消 x 的例子
=> k(ax + by = c) - a(kx + fy = s)
消元后 => bky - afy = ck - sa
=> y = (ck -sa)/(bk -af)
// k(ax + by = c) - a(kx + fy = s)//消元后 => bky - afy = ck - sa
// => y = (ck -sa)/(bk -af)let y = (ck -sa)/(bk -af)
y // 3
let x = (c - by)/a
x // 2
3.优化封装
1. 函数封装好返回对象
function DivideTwoCellOnce (a = 0,b = 0,c = 0,k = 0,f = 0,s = 0 ){if(a === 0 || b === 0 || c === 0 || k === 0 || f === 0 || s === 0) throw '常量输入不完整'let y = (c*k -s*a)/(b*k -a*f)let x = (c - b*y)/a return {x,y}
}// x+2y=5 2x+6y=14
DivideTwoCellOnce(1,2,5,2,6,14) //{x:1,y:2}
2.优化JavaScript在小数运算方面的bug频出
function DivideTwoCellOnce (a = 0,b = 0,c = 0,k = 0,f = 0,s = 0){if(a === 0 || b === 0 || c === 0 || k === 0 || f === 0 || s === 0) throw '常量输入不完整' //优化小数计算buglet maxLength = null;Object.keys(arguments).some(item => {let lings = arguments[item].toString()let lingsL = lings.substring(lings.indexOf('.')+1).lengthmaxLength = lingsL > maxLength ? lingsL:maxLength})a = a*Math.pow(10,maxLength)b = b*Math.pow(10,maxLength)c = c*Math.pow(10,maxLength)k = k*Math.pow(10,maxLength)f = f*Math.pow(10,maxLength)s = s*Math.pow(10,maxLength)let y = (c*k -s*a)/(b*k -a*f)let x = (c - b*y)/areturn {x,y}
}
这篇关于js 解二元一次方程组(消元法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!