How to calculate with imaginary numbers in JavaScript?

后端 未结 3 1410
一生所求
一生所求 2020-12-03 14:05

Recently, I am trying to calculate using some equations that involve the imaginary number i in them. However, unlike e or π

相关标签:
3条回答
  • 2020-12-03 14:14

    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
    
    0 讨论(0)
  • 2020-12-03 14:15

    Assuming you really want complex numbers, and not just the imaginary component:

    I would model a complex number just as you would model a 2D point, i.e. a pair of numbers.

    Just as a point has x and y components, so a complex number has real and imaginary components. Both components can just be modeled with ordinary numeric types (int, float, etc.)

    However, you will need to define new functionality for all of the mathematical operations.

    Addition and subtraction of complex numbers works the same way as addition and subtraction of points - add the separate components to each other, don't mix them. For example:

    (3+2i)+(5+4i) = (8+6i)

    Multiplication works just like you learned in algebra when multiplying (a+b)*(c+d) = (ac+ad+bc+bd).

    Except now you also have to remember that i*i = -1. So:

    (a+bi)*(c+di) = (ac+adi+bci+bdii) = (ac-bd) + (ad+bc)i

    For division and exponentiation, see http://en.wikipedia.org/wiki/Complex_number

    0 讨论(0)
  • 2020-12-03 14:29

    I'm not math expert but I tried to search with another term and I got different results.

    Check these:

    • Complex numbers in JavaScript
    • Complex.js: A complex number class
    • Javascript-Complex-Math-Library

    I hope this helps.

    0 讨论(0)
提交回复
热议问题