Javascriptで複素数を扱うライブラリ
※この記事は古すぎてもう動かないのでこちらを参照。
以下は記録としてだけ。
ーーーーーーーーーーーーーーーーーーーー
練習を兼ねて作ってみた。ソースリストは最後のほうにつけてます。使い方は
(作成) a = new Complex(1,1);
(足し算) c = Complex.cadd(a, b);
(引き算) c = Complex.csub(a, b);
(掛け算) c = Complex.cmul(a, b);
(割り算) c = Complex.cdiv(a, b);
(べき乗) c = Complex.cpow(a, b);
(exp) c = Complex.cexp(a);
(log) c = Complex.clog(a);
とかでOK。
---------------------
function Complex(x, y) {
this.x = x;
this.y = y;
return this;
}
Complex.cadd = function (a, b) {
return Complex(a.x+b.x, a.y+b.y);
}
Complex.csub = function (a, b) {
return Complex(a.x-b.x, a.y-b.y);
}
Complex.cmul = function (a, b) {
return Complex(a.x*b.x-a.y*b.y, a.x*b.y+a.y*b.x);
}
Complex.cdiv = function (a, b) {
r2= b.x*b.x + b.y*b.y;
return Complex((a.x*b.x+a.y*b.y)/r2, (-a.x*b.y+a.y*b.x)/r2);
}
Complex.cconj = function (a) {
return Complex(a.x, -a.y);
}
Complex.cexp = function (a) {
return Complex(Math.exp(a.x)*Math.cos(a.y),Math.exp(a.x)*Math.sin(a.y));
}
Complex.clog = function (a) {
r2= a.x*a.x + a.y*a.y;
return Complex(0.5*Math.log(r2), Math.atan2(a.y,a.x));
}
Complex.cpow = function (a, b) {
return Complex.cexp(Complex.cmul(Complex.clog(a),b));
}
function cabs(a) {
return Math.sqrt(a.x*a.x+a.y*a.y);
}
function carg(a) {
return Math.atan2(a.y,a.x);
}
« 「平家伝説殺人事件」を読んだ。 | トップページ | 相対論的水素原子のエネルギー準位(Dirac方程式の解)をkeisan.casio.jpにUP! »
「パソコン・インターネット」カテゴリの記事
「学問・資格」カテゴリの記事
コメント
« 「平家伝説殺人事件」を読んだ。 | トップページ | 相対論的水素原子のエネルギー準位(Dirac方程式の解)をkeisan.casio.jpにUP! »


Complex.prototypeにメソッドを追加するとクラスメソッドの呼び出しではなくインスタンスメソッドにできます。
function Complex(x = 0, y = 0) {
this.real = x
this.imag = y
return this
}
Complex.prototype.toString = function() { return `${this.real}+${this.imag}i` }
Complex.prototype.cadd = function(n) { return new Complex(this.real + n.real, this.imag + n.imag) }
Complex.prototype.csub = function(n) { return new Complex(this.real - n.real, this.imag - n.imag) }
let a = new Complex(1, 1)
let b = new Complex(2, 3)
console.log("a = " + a)
console.log("b = " + b)
console.log("a + b = " + a.cadd(b))
console.log("a - b = " + a.csub(b))
console.log(a instanceof Complex)
これができると、演算子オーバーロードが欲しくなりますね。
投稿: えぐち | 2021年11月20日 (土) 17時06分