js复数类的学习和使用

function Complex(R , I){
  if( isNaN( R ) || isNaN( I )) { throw new TypeError('Complex params require Number'); }
  this.r = R;                          
  this.i = I;                         
}
// 加法
Complex.prototype.add = function (that) {
  return new Complex(this.r + that.r, this.i + that.i);
};
// 负运算
Complex.prototype.neg = function () {
  return new Complex(-this.r, -this.i);
};
// 乘法
Complex.prototype.multiply = function (that) {
  if (this.r === that.r && this.i + that.i === 0) {
    return this.r * this.r + this.i * this.i
  }
  return new Complex(this.r * that.r - this.i * that.i, this.r * that.i + this.i * that.r);
};
// 除法
Complex.prototype.divide = function (that) {
  var a = this.r;
  var b = this.i;
  var c = that.r;
  var d = that.i;
  return new Complex((a * c + b * d) / (c * c + d * d), (b * c - a * d) / (c * c + d * d));
};
// 模长
Complex.prototype.mo = function () {
  return Math.sqrt(this.r * this.r + this.i * this.i);
};
Complex.prototype.toString = function () {
  return "{" + this.r + "," + this.i + "}";
};
// 判断两个复数相等
Complex.prototype.equal = function (that) {
  return that !== null && that.constructor === Complex && this.r === that.r && this.i === that.i;
};
Complex.ZERO = new Complex(0, 0);
Complex.ONE  = new Complex(1, 0);
Complex.I    = new Complex(0, 1);
// 从普通字符串解析为复数
Complex.parse = function (s) {
  try {
    var execres = Complex.parseRegExp.exec(s);
    return new Complex(parseFloat(execres[1]), parseFloat(execres[2]));
  } catch (e) {
    throw new TypeError("Can't parse '" + s + "'to a complex");
  }
};
Complex.parseRegExp = /^\{([\d\s]+[^,]*),([\d\s]+[^}]*)\}$/;
// console.log(/^\{([\d\s]+[^,]*),([\d\s]+[^}]*)\}$/.exec('{2,3}'));
// 示例代码
var c = new Complex(2, 3);
var d = new Complex(2, 5);

console.log(c.add(d).toString());
console.log(Complex.parse(c.toString()).add(c.neg()).equal(Complex.ZERO));
console.log(c.divide(d).toString(), Complex.parse('{2h, 09d}').mo())
// 共轭复数 得出的结果是普通实数了
console.log(new Complex(2, 3).multiply(new Complex(2, -3)))
{4,8}
true
{0.6551724137931034,-0.13793103448275862} Complex { r: 2, i: 9 }
13
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值