@blog.justoneplanet.info

日々勉強

JavaScript Complex Class(複素数のクラス)

以下のように複素数のクラスを定義することができる。

function Complex(real, imaginary){
    this.x = real;
    this.y = imaginary;
}
Complex.prototype.magnitude = function(){
    return Math.sqrt(this.x * this.x + this.y * this.y);
}
Complex.prototype.negative = function(){
    return new Complex(-this.x, -this.y);
}
Complex.prototype.add = function(cmp){
    return new Complex(this.x + cmp.x, this.y + cmp.y);
}
Complex.prototype.multiply = function(cmp){
    return new Complex(this.x * cmp.x - (this.y * that.y), this.x * cmp.y + this.y + cmp.x);
}
Complex.prototype.toString = function(){
    return '{' + this.x + ', ' + this.y + '}';
}
Complex.prototype.equals = function(cmp){
    return this.x === cmp.x && this.y === cmp.y;
}
Complex.prototype.valueOf = function(){
    return this.x;
}
Complex.sum = function(a, b){
    if(a instanceof Complex && b instanceof Complex){
        return new Complex(a.x + b.x, a.y + b.y);
    }
    else{
        return new TypeError();
    }
}
Complex.product = function(a, b){
    if(a instanceof Complex && b instanceof Complex){
        return new Complex(a.x * b.x - (a.y * b.y), a.x * b.y + a.y * b.x);
    }
    else{
        return new TypeError();
    }
}
var a = new Complex(1, 5);//1+5i
alert(a);//{1, 5}

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment