# 2 * 2 * 2 * 2 or pow(2, 4)?

Discussion in 'C++' started by Olumide, Jun 13, 2008.

1. ### OlumideGuest

Hi ,

I hope this isn't too trivial to ask, but I'm evaluating a polynomial
that involve lots of terms like x^2y^2z^3, and although I can use the
power function pow(a, b), I wonder if just writing x*x*y*y*z*z*z for
example wouldn't be more efficient than pow(x, 2)*pow(y, 2)*pow(z,3).
Or is it all the same?

Thanks,

- Olumide

Olumide, Jun 13, 2008

2. ### Kai-Uwe BuxGuest

Olumide wrote:

> I hope this isn't too trivial to ask, but I'm evaluating a polynomial
> that involve lots of terms like x^2y^2z^3, and although I can use the
> power function pow(a, b), I wonder if just writing x*x*y*y*z*z*z for
> example wouldn't be more efficient than pow(x, 2)*pow(y, 2)*pow(z,3).
> Or is it all the same?

There is no way to tell a priory. You have to measure.

However, if your polynomial has "lots of terms" like those, you might want
to try the Horner scheme of evaluating polynomials:

a_5 x^5 + a_4 x^4 + a_3 x^3 + a_2 x^2 + a_1 x^1 + a_0

can be rewritten as

( ( ( ( a_5 * x + a_4 ) * x + a_3 ) * x + a_2 ) * x + a_1 ) * x + a_0

which uses only 5 multiplications and 5 additions.

Best

Kai-Uwe Bux

Kai-Uwe Bux, Jun 13, 2008

3. ### Daniel PittsGuest

Kai-Uwe Bux wrote:
> Olumide wrote:
>
>> I hope this isn't too trivial to ask, but I'm evaluating a polynomial
>> that involve lots of terms like x^2y^2z^3, and although I can use the
>> power function pow(a, b), I wonder if just writing x*x*y*y*z*z*z for
>> example wouldn't be more efficient than pow(x, 2)*pow(y, 2)*pow(z,3).
>> Or is it all the same?

>
> There is no way to tell a priory. You have to measure.
>
> However, if your polynomial has "lots of terms" like those, you might want
> to try the Horner scheme of evaluating polynomials:
>
> a_5 x^5 + a_4 x^4 + a_3 x^3 + a_2 x^2 + a_1 x^1 + a_0
>
> can be rewritten as
>
> ( ( ( ( a_5 * x + a_4 ) * x + a_3 ) * x + a_2 ) * x + a_1 ) * x + a_0
>
> which uses only 5 multiplications and 5 additions.
>
>
> Best
>
> Kai-Uwe Bux

Which is also an easy way to convert a string representation of a number
into the number itself

--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Daniel Pitts, Jun 14, 2008