2

I'm trying to build a polynomial function generator, so that it takes a vector (arbitrary size) as argument, and generates a polynomial function I can use later.

for instance,

poly_gen(vector<int> power_index)

returns a function (or by other method) in forms of (that i can call with another function)

y(k)=a0+ a1*n+ a2*n^2 + a3*n^3 + ... + ak*n^k

where a0,a1....ak are stored in the vector- power_index

and later I can call it with

int calc_poly(int n)

and this calc_poly can return me a number, calculated by using the polynomial expression generated by poly_gen()

PS: I don't know how to search this question by key words. function,construction, generator, pointer, functor... didn't give me the desired results.

thank you all!

Puppy
  • 144,682
  • 38
  • 256
  • 465
digit plumber
  • 1,140
  • 2
  • 14
  • 27
  • This relation question could be useful to you: http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int – Emile Cormier May 04 '11 at 22:42

2 Answers2

5

You can't generate functions at runtime in C++, so you're going to have to go with a functor.

You can create an object that stores the coefficients given by power_index in some manner (perhaps a direct copy), and give it an operator() (int n) operator that will take the coefficients and calculate the value of the polynomial (Horner's rule?). Then you can pass that object around freely.

So, you need a constructor, an internal representation of the coefficients, and an operator() that does the actual calculation. Should be simple enough.

David Thornley
  • 56,304
  • 9
  • 91
  • 158
  • 1
    well technically you could generate assembly code during runtime and jump to that code – Doug T. May 04 '11 at 21:43
  • @Doug T: Maybe. There have been systems (probably still are) that don't allow execution of process-writable memory (don't know how they would handle a Lisp compiler or JIT compilers). In any case, it would be very system-specific. – David Thornley May 05 '11 at 13:41
1

There was a nice "rosetta stone" question on (almost) this very problem a while back.

There are several C++ answers there: one using boost::lambda, one using a more conventional approach, and one using MPL (and also a C++0x version, which IMHO would be the ideal solution if your compiler supports it). Obviously the simple quadratic there will need generalizing to arbitrary numbers of powers but that's simple enough compared with getting your head around the function object concept.

Community
  • 1
  • 1
timday
  • 24,582
  • 12
  • 83
  • 135