【问题标题】:Polynomial Multiplication with Complex Numbers Class复数多项式乘法类
【发布时间】:2015-09-25 17:31:06
【问题描述】:

指向我的代码的 Gist 链接。 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。所以,看起来有些东西加倍了,但我不知道为什么。

谁能弄清楚为什么乘法不正确?

【问题讨论】:

  • else 之后缺少{ }
  • 在此处发布您的相关代码以及您的问题,而不是在链接中。如果这里发布的代码太多,那么请志愿者通过的代码就太多了。
  • 发布您遇到问题的相关代码。

标签: java arrays multiplication complex-numbers polynomial-math


【解决方案1】:

正如 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 做到了,你也应该这样做!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多