Calling more complicated functions of a x in a Self-Defined Function

Hi all, I am tying to code an integral calculator as C++ practice over summer. I am able to find out how to include simple mathematical functions such as exp in the function. However, I am unable to integrate more complicated functions such as (x^3) and (exp + sin). Does anyone have any advice how I can incorporate this into the code below. Many Thanks



#include <fstream>
#include <vector>
#include <string> //
#include "stdafx.h"
#include <iostream>
#include <math.h>

using namespace std;

//function that divides a mathematical function into steps and sums the area of each step

double integral(double(*f)(double x), double a, double b, int n) {
double step = (b - a) / n;
cout << step << "\n";
double totalArea = 0.0;
for (int i = 0; i < n; i++) {
totalArea += f(a + (i + 0.5) * step) * step;
}
return totalArea;
}
int main() {
cout.precision(7);
cout << integral(exp, 0, 1, 10000)<< "\n"; // want to replace exp with different functions of x
return 0;
}
If you're using function pointers, you have to pass in a pointer.

Make a function called exp_plus_sin(double x) { ... }, and make it return exp(x) + sin(x);.

Also, please prefer to use <cmath> instead of <math.h>. math.h is the old C library, cmath is C++.

If you want to be able to evaluate arbitrary functions, you have to parse input correctly and form what's called an expression tree. It can be a lot of work, but certainly possible. Languages like Wolfram Mathematica can parse symbolic equation input.
https://en.wikipedia.org/wiki/Binary_expression_tree
Last edited on
Topic archived. No new replies allowed.