【问题标题】:Java-Junit: multiplying 2 polynomial expressionsJava-Junit:乘以 2 个多项式表达式
【发布时间】:2012-11-17 19:07:07
【问题描述】:

我正在创建一种将 2 个多项式表达式相乘的方法,这样:

3x^5 * 2x^3 = 6x^8 -> 系数相乘,指数相加。

我的测试用例如下所示

@Test
public void times01() throws TError { 
    assertEquals(Term.Zero, Term.Zero.times(Term.Zero)); 
}

我还应该补充一点 Term.Zero = (0,0)Term.Unit = (1,0) 所以任何乘以 Term.ZeroTerm.Zero 任何乘以 Term.Unit 都返回自身为 Term.Unit 实际上是 1。

public Term times(Term that) throws CoefficientOverflow, ExponentOverflow, NegativeExponent {
    return null;
}

这是times 方法。我正在寻求一些有关编码times 方法的帮助?我发现的问题是如何处理 3 个 Term 对象,Term1Term2Term3,而不是使用无穷无尽的 if-statements

【问题讨论】:

    标签: java if-statement junit polynomial-math multiplication


    【解决方案1】:

    到目前为止,我已经设计了以下伪代码:

    Term1 == Term.Zero OR Term2 == Term.Zero => Term3 = Term.Zero
    Term1 == Term.Unit => Term3 = Term2
    Term2 == Term.Unit => Term3 = Term1
    
    Term1.coef * Term2.coef = Term3.coef
    Term1.expo * Term2.expo = Term3.expo
    

    使用以下代码

    @SuppressWarnings("null")
    public Term times(Term that) throws CoefficientOverflow, ExponentOverflow, NegativeExponent {
        Term term1 = new Term(coef,expo);
        Term term2 = that;
        Term term3 = null;
    
        if(term1 == Zero || term2 == Zero) {
            term3 = Zero;
        } else if(term1 == Unit) {
            term3 = term2;
        } else if(term2 == Unit) {
            term3 = term1;
        } else if(term1.coef == 2 && term1.expo == 0) {
            term3.coef = term2.coef * 2;
            term3.expo = term2.expo;
        } else if(term2.coef == 2 && term2.expo == 0) {
            term3.coef = term1.coef * 2;
        term3.expo = term1.expo;
        } else {
            term3.coef = term1.coef * term2.coef;
            term3.expo = term1.expo + term2.expo;
        }
    
    
    
        return term3;
    }
    

    但这让我不得不将 Term 类中的“coef/expo”变量从

    final private int coef;
    

    private int coef;
    

    这会在以下测试中出现错误...

    @Test
    public void times09() throws TError { assertEquals(new Term(min,2), new Term(hmin,2).times(new Term(2,0))); }
    

    有什么想法吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      相关资源
      最近更新 更多