polynomials in c++

Discussion in 'C++' started by Matthias, Mar 27, 2007.

  1. Matthias

    Matthias Guest

    how do i make a program that gets numbers from a user. and then stores
    it into an array. using polynomials
    if the user entered 7 5 4 3 2
    the polynomial would be 7x^4+5x^3+4x^2+3x+2
    the program would then ask for a value of x, and solve it.

    i think i got an idea how it would store plain old numbers into an
    array. but not sure how it would store a polynomial into an array.
    does anyone have any ideas?
     
    Matthias, Mar 27, 2007
    #1
    1. Advertisements

  2. Matthias

    Jim Langston Guest

    Easist way, just store the numbers the user enters. Then get the value for
    x. Then after you have all the data calculate the polynomal.
     
    Jim Langston, Mar 27, 2007
    #2
    1. Advertisements

  3. Matthias

    Kai-Uwe Bux Guest

    Use a vector. The polynomial

    a_0 + a_1 x + a_2 x^2 + ... + a_n x^n

    will be stored as the sequence

    (a_0,a_1,...,a_n)

    You can put that into a polynomial class. It would contain a vector as its
    only data member. One way to go is to have as an invariant of the class
    that the highest order element in the vector is always non-zero (the empty
    vector will then represent the 0-polynomial). Alternatively, you would have
    to provide a tweaked operator==. It is straight forward to implement the
    usual arithmetic operations such as +,-,*, and evaluation at a value. In
    order to make polynomials cooperate nicely with std::set<> and the like,
    you also will want to implement operator< or specialize std::less<>.


    Best

    Kai-Uwe Bux
     
    Kai-Uwe Bux, Mar 27, 2007
    #3
  4. C++ doesn't have polynomials as built-in data types, so you'll have to write
    your own code for polynomials, like:

    class Polynomial
    {
    protected:
    std::vector<int> m_Coefficients;
    public:
    Polynomial (std::vector<int> Coefficients);
    double ComputeValue (double x);
    };

    double Polynomial::ComputeValue (double x)
    {
    // Use Heron's formula to calculate the result.
    for (std::vector<int>::iterator it = m_Coefficients.begin ();
    it != m_Coefficients.end (); it++)
    {
    // TODO: Implementation needed here.
    }
    }


    Regards,
    Stuart
     
    Stuart Redmann, Mar 27, 2007
    #4
  5. Matthias

    sergejusz Guest

    Hi,
    just small remark. I think you mean Horner's rule:
    7x^4+5x^3+4x^2+3x+2 = (((7x+5)x+4)x+3)x+2

    Kind regards
    Serge
    http://www.sergejusz.com
     
    sergejusz, Mar 28, 2007
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.