如何在JavaScript中使用虚数进行计算? [英] How to calculate with imaginary numbers in JavaScript?

查看:141
本文介绍了如何在JavaScript中使用虚数进行计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在尝试使用一些涉及虚数 i 的方程式进行计算.但是,与 e π不同,没有任何方法或本机函数会返回 i . Google中的快速搜索并没有给我任何答案.关于如何实现它的任何想法?

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;

推荐答案

假设您确实需要复数,而不仅仅是虚数:

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

我将对复杂数字进行建模,就像对2D点(即一对数字)进行建模一样.

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

就像一个点一样,它具有x和y分量,因此复数具有实部和虚部. 这两个组件都可以使用普通的数值类型(int,float等)建模

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)

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

乘法的工作原理就像您在乘(a + b)*(c + d)=(ac + ad + bc + bd)时在代数中学到的一样.

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

除了现在,您还必须记住i * i = -1.所以:

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

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

有关除法和取幂的信息,请参见 http://en.wikipedia.org/wiki/Complex_number

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

这篇关于如何在JavaScript中使用虚数进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆