Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing math expression to function

Tags:

c++

function

math

I need to make function in C++ to calculate integrals. I am using the simpsone rule to calculate value of the given integral. I know how to calculate that. I don't have any problem with math. I need to know how can I pass whole expression to make my program flexible.

I have 4 f(x) functions for which I should make calculations. For example:

f(x)=2e^x
f(x)=x^3e
etc.

I have two options to make it.

1)I can do separate function for each f(x) function.

double function1() {
...
calculations 2e^x
...
return resault;
}

double function2() {
...
calculations x^3e
...
return resault;
}

This way is easy and fast to write, but the code is not flexible at all. In this case I need to make new function for every new given f(x) function.

I would like to have one function to which I can pass selected f(x) function.

2) Second case I prefer is to make some kind of interpreter of expressions. I thought about putting the parts of expression into std::vector and then making calculations for each cell of vector.

I've seen already an idea to parse string to the expression, but I think at the end it will be almost the same as idea with vector. I can be wrong.

What is the best way to make my code flexible and easy to use for users(not programmers)?

like image 647
Iomanip Avatar asked Apr 29 '26 20:04

Iomanip


1 Answers

Suppose you have a function that takes two expressions and returns sum of the results of them. You can pass the expressions to function using lambda expression which is supported since C++11 as follow:

template<typename Func, typename Func2>
int calculate(Func &lambda_expr1, int param1, Func2 &lambda_expr2, int param2)
{
    return lambda_expr1(param1) + lambda_expr2(param2);
}

void main()
{
    // case 1
    auto f1 = [](int p) {return p*p; }; // expression 1
    auto f2 = [](int p) {return p*p*p; }; // expression 2
    int result = calculate(f1, 3, f2, 4);
    // result = 73

    // case 2
    result = calculate([](int p) {return p*p/2; }, 4, [](int p) {return p*p*p/3; }, 3);
    // result = 17
}
like image 157
Hossein Golshani Avatar answered May 01 '26 11:05

Hossein Golshani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!