简体   繁体   中英

Is there a way to evaluate user input as a function? (C++)

I'm designing a program that can do some math stuff for personal use, think things like numerical integrations and taylor series. For example, say I want to do a taylor expansion on e^x. It has to perform that operation many times in multiple different contexts, so I define it with a function and let the other functions call it when they need it. The problem is that if I want to change the mathematical expression I'm working on, I have to directly edit the source file with that new expression. I'm wondering if there's a way I can input the function at runtime, such as how you could do it on WolframAlpha .

I searched around and discovered the eval() function, but that seems to be specifically a JS thing and highly taboo. I also found the "command pattern", but I'm not exactly certain how it works and it looks like it would need predefined commands anyway.

Below is how I've been defining the mathematical expression:

double func::define(double x) {
    return pow(e, x);
}

And here is an excerpt of a function that makes use of it:

double finidx::dxatpoint(double x) {


    int size = this->approx.coeffs.size();
    double sum = 0;
    for (int i = 0; i < size; i++) {
        double point = this->approx.samps[i];

        double x = this->getx() + (point * h);


        double ans = this->define(x);

        ans *= this->approx.coeffs[i];


        sum += ans;


    }

Thanks in advance!

You could use this for evaluating mathematical expressions.

  1. very simple to use
  2. just include it in your source code

alternatively you could write your own parser for expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM