java - 复数类多项式乘法

标签 java arrays multiplication complex-numbers polynomial-math

要点链接到我的代码。 The problem I'm having uses the class Polynomial, method multiply, lines 136-172.

方法如下:

public Polynomial multiply(Polynomial right){
    int size = right.length + length -1;
    int i;
    int r;
    Complex productCoeff;

    Complex coeffP = new Complex();
    Complex coeffQ = new Complex();
    Complex currentValue;

    Polynomial temp = new Polynomial(size);

        for (i = 0; i < length; i++)
        {
            for (r = 0; r < right.length; r++) {
                coeffP = (retrieveAt(i));
                coeffQ = (right.retrieveAt(r));

                productCoeff = coeffP.multiplyComplex(coeffQ);


                if (temp.retrieveAt(i+r) == null)
                    currentValue = productCoeff;

                else

                    currentValue = (temp.retrieveAt(i+r));
                    currentValue = currentValue.addComplex(productCoeff);

                temp.replaceAt(i+r, currentValue);

            }
        }

    return temp;
}

我获得了多项式类,并尝试实现复数的加法、减法和乘法。类多项式的工作原理是将系数存储到数组中。 [x^0, x^1, x^2, x^3 ...] 我得到了可以处理复数的加法和减法,但是我无法让乘法正常工作。

我对复数相乘的思考过程:对于第一个数组中循环的每个项目,我想循环第二个数组中的所有项目并相乘。在每一系列乘法之后,我想将该值存储到临时数组中。如果临时数组在该位置有一个值,我想将相乘的值添加到临时数组中该位置存储的值。如果临时数组中的该位置没有值,我可以简单地替换它。

该方法适用于正则多项式,但是当使用复数时,我得到了错误的答案。例如:

((1+2i)+(3+4i)x) ((2+7i)+(4+3i)x) 应等于 (-12+11i) + (-24+40i)x + (25i)x^2 但当我运行程序时,我的答案是 (-24+22i) + (-26+51i)x + (50i)x^ 2. .所以,看起来有些东西被加倍了,但我不明白为什么。

谁能找出为什么乘法不正确吗?

最佳答案

正如 saka1029 已经提到的:您的代码缩进与其逻辑结构不匹配。你的 if-else 结构

if (temp.retrieveAt(i+r) == null)
    currentValue = productCoeff;

else

    currentValue = (temp.retrieveAt(i+r));
    currentValue = currentValue.addComplex(productCoeff);

实际上会被解释为

if (temp.retrieveAt(i+r) == null) {
    currentValue = productCoeff;
} else {
    currentValue = (temp.retrieveAt(i+r));
}

currentValue = currentValue.addComplex(productCoeff);

这意味着最后一行将在 for 循环的每次迭代中执行,无论上述条件产生什么结果。即使它看起来很迂腐,我总是写大括号以避免像这样的难以跟踪的错误。请参阅Is it ok if I omit curly braces in Java? 。如果乔恩·斯基特(Jon Skeet)做到了,你也应该这么做!

关于java - 复数类多项式乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281933/

相关文章:

c++ - 为什么 Strassen 矩阵乘法比标准矩阵乘法慢得多?

arrays - Swift 中复杂向量的乘法

java - 当我尝试将 google 地点库添加到我的项目时出现问题

java - 我的代码正在打印每一个字,它不应该

java - 如何收集多个异步回调?

c++ - 用输入表示数组中元素的数量吗?

arrays - C++ 新手 - 无法获取指向数组的指针来工作

ios - 图像数组和每帧 Xcode 的 if 语句

javascript - 3 乘以 1.1 时出现奇怪的结果

java - 如何将 HTTP POST 请求从 Servlet 发送到外部 Web 服务?