# polynomials in c++

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

1. ### MatthiasGuest

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

2. ### Jim LangstonGuest

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

3. ### Kai-Uwe BuxGuest

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
4. ### Stuart RedmannGuest

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
5. ### sergejuszGuest

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