开发者

Derivate of function in c

is there any way to calculate the values of the partial derivates of a function in c, which is unknown so far? I read here: Compute a derivative using discrete methods about how to implement the derivate, which is only possible when I know exactly the function f(x) with x=(x0,x1,...,xn). But what, if I want to pass the function f(x) as parameter, is this somehow possible? I imagine that not because I would need to somehow parse the string (must be passed as string obviously, like 'x0*exp(x1)*ln(x2*x1)')!? thanks so far!

edit: My question isn't about how to pass a function as a pointer in c, but about how to evaluate a mathematical function 开发者_高级运维which is e.g. entered by the user as string.


You could pass in some sort of parse-tree representing the expression instead of a string. Symbolic differentiation is an easy and completely mechanical task for non-implicit functions, so differentiating an expression once you've decided how to represent it would be relatively easy.


Perform a search on function pointers in C, that should help you.

edit: adding an example so it is more obvious yet...

#include <stdio.h>

typedef float (*real_univariate_function)(float x);

float calculate_derivative(real_univariate_function f, float x, float h) {
    return (f(x+h)-f(x))/h;
}

float square(float x) {
    return x*x;
}

int main() {
    printf("derivative for x^2 in 2 with h 0.001 is: %f\n",
            calculate_derivative(&square, 2, 0.001));
}

there might be some syntax errors, my C is getting rusty...


I know I'm late, but maybe this can help someone. I've written a library that does exactly that: https://github.com/B3rn475/MathParseKit

You can parse a string into a function tree and compute the derivatives.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜