Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

math - How to calculate with imaginary numbers in JavaScript?

Recently, I am trying to calculate using some equations that involve the imaginary number i in them. However, unlike e or π, there isn't any methods or native functions that will return i. A quick search in Google didn't get me any answer. Any ideas on how to achieve it?

function imaginary(){
    return {
        rational: this,
        imaginary: "2i"  //magic code that does this
    };
};
Number.prototype.imaginary = imaginary;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The math.js library supports complex numbers, matrices, and more. The library is compatible with JavaScript's built-in Math library, so quite easy to use.

http://mathjs.org

You can just do things like:

math.i;                         // i
math.sqrt(-4)                   // 2i
var a = math.complex('2 + 3i'); // 2 + 3i
var b = math.complex(4, 5);     // 4 + 5i
math.add(a, b);                 // 6 + 8i
math.multiply(a, b);            // -7 + 22i
math.eval('e^(pi*i) + 1');      // ~0
// etc...

Edit: note that math.js comes with an expression parser, which makes it more convenient to work with complex values and mathematical expressions:

math.eval('(2 + 3i) * (4 + 5i)'); // -7 + 22i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...