数据结构之“Ordered List and Sorted List”(四)

        本文主要介绍“Ordered List”的一种应用——“多项式求导”。(点击打开链接


一、名字介绍

        本文的数学公式比较多,我就不在博客中编公式了,在此简单列一下几个高数名词。

        polynomial    ——  多项式

        coefficient     ——  系数

        exponent       ——  指数

        derivative      —— 导数

        differentiation —— 微分


二、数学理论

        利用“Ordered List”进行多项式求导,它在数学上,首先要将多项式表示为“系数-指数对”序列,即“An alternative representation for such a polynomial consists of a sequence of ordered pairs”。然后在观察原始多项式和求导后的多项式“系数-指数对”序列的变化,寻找规律。原文如下:


方法就是:

1,丢弃指数为零的项;

2,对于其他项,将其系数修改为“系数与指数的乘积”,再将其指数减一,如此即可。


三、编程实现

1,“系数-指数对”抽象为“Term”;

2,多项式继承自“ListAsLinkedList”。

#pragma once
#include "ListAsLinkedList.h"

// the oredered pair
class Term : public Object
{
public:
    Term(double, unsigned int);
    void Put(std::ostream &)const;
    void Differentiate();

protected:
    int CompareTo(Object const &) const;

private:
    double coefficient;
    unsigned int exponent;
};


class Polynomial : public ListAsLinkedList
{
public:
    void Differentiate();
};


class DifferentiatingVisitor : public Visitor
{
public:
    void Visit(Object & object)
    {
        Term & term = dynamic_cast<Term&> (object);
        term.Differentiate();
    }
};


实现

#include "stdafx.h"
#include "PolynomialDifferentiate.h"


Term::Term(double _coefficient, unsigned int _exponent)
    : coefficient(_coefficient)
    , exponent(_exponent)
{
}

void Term::Put(std::ostream & s) const
{
    s << typeid(*this).name() << " {";
    s << coefficient << "," << exponent;
    s << " }";
}

void Term::Differentiate()
{
    if (exponent > 0)
    {
        coefficient *= exponent;
        --exponent;
    }
    else
        coefficient = 0;
}

int Term::CompareTo(Object const & object) const
{
    Term const & term = dynamic_cast<Term const &> (object);
    if (exponent == term.exponent)
        return ::Compare(coefficient, term.coefficient);
    else
        return exponent - term.exponent;
}

 void Polynomial::Differentiate()
{
    DifferentiatingVisitor visitor;
    Accept(visitor);
    Object & zeroTerm = Find(Term(0, 0));
    if (!zeroTerm.IsNull())
    {
        Withdraw(zeroTerm);
        //delete & zeroTerm;
    }
}


四、测试

    // test for Polynomial Differentiate
    {
        Polynomial polynomial;
        Term pArray[] = { Term(5,0), Term(32,1), Term(4,2), Term(56,3), Term(16,4), Term(45,5) };
        for (unsigned int i = 0; i < 5; ++i)
            polynomial.Insert(pArray[i]);

        polynomial.Differentiate();
        polynomial.Put(std::cout);
        polynomial.RescindOwnership();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值