writes:
>> The magic phrase is "function pointer."
>>
>> double func(double x1, double x2)
>> {
>> return 19.739208802178717237668981999752
>> / (3 * (x1+x2)*(x1+x2)*(x1+x2))
>> + x1 * x2;
>> }
>>
>> result_type minimize(various_params,
>> double (*fptr)(double,double),
>> more_params)
>> {
>> ...
>> z = fptr(x, y);
>> ...
>> }
>>
>> ...
>> result = minimize(params, func, other_params);
The above was written by Eric Sosman. Google Groups automaticalloy
inserts an attribution line for quoted material, a line of the form
"So-and-so writes:". Please don't delete that line; it makes it
easier to follow the discussion.
> Ok, this is some solution. But in this case, the function has to be
> directly programmed by programmer. What if user would type the
> function and then the input would be parsed by some parser. How can
> the function can be coded then?
The only pure C solution I can think of is to write your own
expression parser that produces a (mostly binary) tree representing
the mathematical function. You can then have a C function, perhaps
called "evaluate", that takes a pointer to the root of the tree and
the values of x1 and x2, and returns the result of evaluating the
mathematical function with those arguments.
It's going to be substantially slower than using a C function
directly; this may or may not matter. It's also going to be
substantially mor work; you'd essentially be doing part of what the
compiler normally does.
Consider that some other languages provide features that could make
this easier. For example, Perl's built-in "eval" function can
directly execute a chunk of Perl code passed as a string. The various
Lisp-like languages provide similar facilities.
Or you could take a C representation of the mathematical function as
input and automatically generate a C source file that you then compile
and execute.
--
Keith Thompson (The_Other_Keith) <kst->
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"