I'm totally new to C. Here's the question:
Write the function
fzero(double f(double),double x1, double x2)
as we did in class and use it to find all the solutions of
sin( pi*x / (1+x^2) ) = 0.25.
Now, I don't want you to solve the this. I'd missed this lecture and only want to understand what means
double f(double);
In that context, it means that f is a function pointer to a function to that takes one double argument, and returns a double.
As an example:
void foo(double f(double))
{
double y = f(3.0); // Call function through function pointer
printf("Output = %f\n", y); // Prints "Output = 9.0000"
}
double square(double x)
{
return x*x;
}
int main(void)
{
foo(&square); // Pass the address of square()
}
Note that there are two syntaxes for function pointers:
void foo(double f(double))
void foo(double (*f)(double))
These are equivalent.
Related
I am trying to calculate the Jacobian matrix (numerical, at a given point) of a given equation. Now, I don't know the dimension of the equation beforehand, so I can't just do something like
static double f(double x1, x2)
{
return x1 * x1 - 2 * x1 * x2;
}
so instead, I am getting the input values as an array like so
static double f(double xArray[])
{
return xArray[0] * xArray[0] - 2 * xArray[1] * xArray[0];
}
void jacobian(double xArray[], double jacob_matrix, size_t size,
double f(double xArray[], size_t))
{
// calculations
}
However, when I try to call the function from main like
int main(void)
{
double x_input[4] = {1., 1., 3., 4.};
double jacob_matrix[4];
jacobian(x_input, jacob_matrix, 4, f(x_input, 4));
return 0;
}
I get incompatible type for argument 4 of 'jacobian' I imagine this has to do with my array being casted into a pointer, but I can't figure out how to fix this.
You need to pass the function pointer to f, not the result of calling f.
Try:
jacobian(x_input, jacob_matrix, 4, f);
For the function signature:
void jacobian(double xArray[], double jacob_matrix, size_t size,
double f(double xArray[], size_t))
For the second argument, if you're going to pass an array you need the argument to be a pointer, double* jacob_matrix or double jacob_matrix[].
For the 4th argument, the passed function arguments should match the caller signature, so in your case you are passing a function which is of type double (*)(double *), but the caller expects a function of type double (*)(double *, size_t), so one of them should be changed to match, either add a second argument to the called function, or remove the second argument of the caller function signature.
#include <stdio.h>
static double f(double xArray[])
{
return xArray[0] * xArray[0] - 2 * xArray[1] * xArray[0];
}
void jacobian(double xArray[], double* jacob_matrix, size_t size,
double f(double xArray[]))
{
printf("%f", f(xArray)); // for example
}
int main(void)
{
double x_input[4] = {1., 1., 3., 4.};
double jacob_matrix[4];
jacobian(x_input, jacob_matrix, 4, f);
return 0;
}
Note that my approach only addresses the code correctness and not the mathematical part, i.e. the jacobian calculation.
I am working on C implementations of calculus operations (such as derivatives, integrals, etc...). As an example, here's the template definition of my derivative function:
double derivative(double (*f)(double), double x);
Let's say I want to compute the derivative of exp at 1, the call would then be: derivative(exp, 1);
Pretty basic stuff. Now my question is, how would I go about (if it is even possible) to pass a composition to my derivative function? I tried passing exp(cos) which got me
error: passing 'double (double)' to parameter of incompatible type 'double'.
How would I do it? Is it even possible?
I think you're asking for this:
double composition(double x) {
return exp(cos(x));
}
derivative(composition, 1);
Many languages allow you to do something like the following, but C doesn't have anon functions:
derivative(x => exp(cos(x)), 1);
If you want some sort of run-time control over the composition, you could write a function that evaluates an array of function pointers as a composition:
// calls functions in reverse order
double compose(size_t n, double (* const fc[])(double), double x)
{
while (n--)
{
x = fc[n](x);
}
return x;
}
This could be called from another version of your derivative function:
double derivative_composed(size_t n, double (* const fc[])(double), double x)
{
// Example implementation for illustrative purpose only.
double fx, fxh, h;
h = x / 1e10;
if (h == 0)
{
h = 1e-10;
}
fx = compose(n, fc, x);
fxh = compose(n, fc, x + h);
return (fxh - fx) / h;
}
To avoid repeated code, your original derivative function could be changed to be a wrapper that calls derivative_composed with a single function:
double derivative(double (* const f), double x)
{
return derivative_composed(1, &f, x);
}
Example usage:
int main(void)
{
double (* const fc[2])(double) = { exp, cos };
double x = 1.0;
double xprime = derivative_composed(2, fc, x);
printf("x = %f, xprime = %f\n", x, xprime);
}
Output:
x = 1.000000, xprime = -1.444407
C does not have any operation for function composition. To compute the derivative of expâcos, you can define a function expcos:
double expcos(double x)
{
return exp(cos(x));
}
and take the derivative of that.
For a more general solution, you could modify your derivative routine to take both a function pointer and a const void * to forward to the function. The function would take the const void * as a parameter, convert it to a pointer to a const structure of a type particular to that function, and take data from that structure. Then function composition can be implemented with a compose function that uses a structure containing two function pointers. However, it would mean you would need to use proxy routines for ordinary functions like exp and cos that accept but ignore the const void *.
I would like to convert
typedef double (*Function)(double s[4]);
double f1 (double x[N]) {return x[0]*x[1];}
Function t = f1;
to something like this:
typedef double (*Function)(double s[4]);
Function t = ({ return x[0]*x[1];});
which returns a "void value not ignored as it ought to be" error.
How can I make this work?
C does not have anonymous functions or lambda expressions. So it is not possible.
EDIT: PSEUDO LAMBDA
Tiny dirty workaround for the compilers which allow nested functions:
#define lmb(rt, fb)({rt fn__fn__fn_ fb fn__fn__fn_; })
int main(void)
{
double (*f)(double x[]) = lmb(double, (double x[]) { return x[0] * x[1]; });
double x[] = {4.0, 5.0};
printf("%f\n", f(x));
}
I am relatively new in C and found the code of this question. How do you pass the argument double (*f)(double) of the function and how does the pointer works out in this?
Here's the function:
double derivative(double (*f)(double), double x0, int order)
My guess was that first you need something like:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double f(double x){
return pow(x,2);
}
int main(){
double x = 2;
int order = 2;
derivative(f(x), x , 2);
}
I tried it but it didn't work. Thanks for the help.
double (*f)(double) is a function pointer. It means you need to pass a pointer to (or just the name of) a function. In your attempt, you're calling the function, then passing the return value, which isn't correct.
The correct way would be:
derivative(f, x, 2);
I have recently stumbled on this curious thought while handling a C code.
I have written a function which returns a double and takes in as argument the pointer to a function and a certain number of parameters, namely
double template_1(double (*)(double),...);
this function correctly identifies a certain property of a real function
double f(double );
represented as a pointer in template_1, in order to maketemplate_1 valid for every real function I might plug-in.
Now I had to write another function, let it be:
double derivative(double (*)(double),double);
double derivative(double (*f)(double),double x){
double epsilon = ...;
return ( f(x+epsilon)-f(x-epsilon) )/(2.0*epsilon);
}
again with f in the argument to make it work for every f.
My question is: since I would like to use derivative in template_1 without modifying it, is it possible to write a function which takes derivative and spits out something that has the form of double (*)(double ) ?
My idea was to define typedef double (*real_function)(double);
and then to define
real_function g(double (*derivative)(double (*)(double),double ) )
which I'd like it to spit out something like: double derivative_2(double x); so that I could define something like g(derivative) = double (*h)( double); directly in template_1 argument
unfortunately I don't have the faintest idea of how to make this work, or even if it can work.
There are a couple ways to do anonymous functions in C. As the comments said, they aren't portable. But depending on the use case you may find this useful: Anonymous functions using GCC statement expressions
A couple of people have seemed to have similar issues, not sure how portable they are but they may be resourceful:
https://github.com/graphitemaster/lambdapp
https://github.com/Leushenko/C99-Lambda
Basically, if there's a way to architect your program in a way that doesn't require anonymous functions, then do it that way. If you have no other option, then I would give one of these a shot.
Warning: I am a C++ developer with little C knowledge so everything that follows is likely unidiomatic C.
As KerrekSB said, you would need to carry some state with your function. This is not possible with raw functions but you can define a struct that carries the state and add a function that works with this struct. This obviously has the drawback of losing the nice function call syntax. I whipped up an example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef double (*raw_fptr)(double);
struct real_function;
typedef double (*evaluate_function)(struct real_function*, double);
struct real_function {
evaluate_function evaluate;
};
typedef struct real_function real_function;
double evaluate(real_function *f, double x) {
if(f) {
return f->evaluate(f, x);
}
return NAN;
}
struct raw_real_function {
real_function real_function_base;
raw_fptr raw_function;
};
typedef struct raw_real_function raw_real_function;
double evaluate_raw_real_function(real_function *f_base, double x) {
if(f_base) {
raw_real_function *f = (raw_real_function*)f_base;
return f->raw_function(x);
}
return NAN;
}
raw_real_function make_raw_real_function(raw_fptr function) {
raw_real_function result;
result.raw_function = function;
result.real_function_base.evaluate = evaluate_raw_real_function;
return result;
}
struct derive_real_function {
real_function real_function_base;
real_function *function_to_derive;
};
typedef struct derive_real_function derive_real_function;
double derive(real_function *f_base, double x) {
derive_real_function *f = (derive_real_function*)f_base;
double epsilon = 1e-3;
double upper = evaluate(f->function_to_derive, x+epsilon);
double lower = evaluate(f->function_to_derive, x-epsilon);
double result = (upper - lower)/(2.0*epsilon);
return result;
}
derive_real_function make_derivative(real_function * function_to_derive) {
derive_real_function result;
result.real_function_base.evaluate = derive;
result.function_to_derive = function_to_derive;
return result;
}
double x_cubed(double x) {
return x * x * x;
}
int main(int argc, char **argv) {
raw_real_function x_cubed_wrapped = make_raw_real_function(x_cubed);
derive_real_function derived = make_derivative(&x_cubed_wrapped.real_function_base);
derive_real_function derived_twice = make_derivative(&derived.real_function_base);
double x = atof(argv[1]);
double derivative = evaluate(&derived.real_function_base, x);
double second_derivative = evaluate(&derived_twice.real_function_base, x);
printf("derivative of x^3 at %f = %f\n", x, derivative);
printf("second derivative of x^3 at %f = %f\n", x, second_derivative);
return 0;
}
See (a slight variaton, due to input limitations) running here.
How does it work? I faked some inheritance with the structs real_function, raw_real_function and derive_real_function to generate virtual function calls. The struct real_function serves as the container of a virtual function table consisting of only the entry evaluate. This function pointer points to the "derived" structs' relevant evaluate function:
raw_real_function instances point to evaluate_raw_real_function (as initialized in make_raw_real_function. derive_real_function instances point evaluate to derive (as initialized in make_derivative).
When calling evaluate on the real_function_base member, it will call the associated evaluation function, which casts the real_function* to it's associated struct pointer and does what is needed with that information.
Since everything is just a real_function*, we can chain them at will but need to convert "normal" functions into the real_function format, that's what make_raw_real_function does.
If you have a function my_fancy_function:
double my_fancy_function (double x) { return sin(x) + cos(x); }
Then, you can use a helper macro that creates the derived function for you.
#define DEFINE_DERIVATIVE_OF(FUNC) \
double derivative_of_ ## FUNC (double x) { \
return derivative(FUNC, x); \
}
DEFINE_DERIVATIVE_OF(my_fancy_function)
You then pass this newly defined function to your template.
template_1(derivative_of_my_fancy_function, x, y, z);