Understanding the following C++ function definition - c++

double randNormal(double (*fun)(double, double, double), double xmin, double xmax, double sigma, double mju)
{
static double (*Fun)(double, double, double) = NULL, YMin, YMax;
static bool First = true;
if (First)
{
First = false;
srand((unsigned) time(NULL));
}
if (fun != Fun)
{
Fun = fun;
YMin = 0, YMax = Fun(xmin, sigma, mju);
for (int iX = 1; iX < 10000; iX++)
{
double X = xmin + (xmax - xmin) * iX / 10000;
double Y = Fun(X, sigma, mju);
YMax = Y > YMax ? Y : YMax;
}
}
double X = xmin + (xmax - xmin) * rand() / RAND_MAX;
double Y = YMin + (YMax - YMin) * rand() / RAND_MAX;
return Y < fun(X, sigma, mju) ? X : randomNormal(Fun, xmin, xmax, sigma, mju);
}
I am very new to C++ and I am struggling with understanding the code above. What is the role of (*fun)(double, double, double) when we define the function randNormal? Furthermore, what is accomplished by the second line starting with static double? I would appreciate your help!

This is a function pointer. In this case to a function that returns a double and takes 3 doubles as an argument. Fun is declared the same way and later called, using 3 doubles as parameters)
The static double line declares a function pointer Fun just as fun and two double values. static here means that the values are preserved and still available when the function is called the next time.
Edit:
To read more about function pointers, see here: How do function pointers in C work?

double (*fun)(double, double, double) is a pointer to a function that takes 3 doubles as argument and returns a double. For example when you have
double example(double a, double b, double c){
return a+b+c;
}
you can pass this function via
double x = randNormal(example,...);
The static Fun keeps its value between function calls. Thats why in the function it is checked, if Fun != fun and only if this is true the parameter is assigned to the static variable. However, to explain better, I would have to know what is the logic of this function.
PS: typedefs can help a lot when working with function pointers. Using
typedef (double)(*FUNCTION_TYPE)(double,double,double);
or more generally,
typedef (return_type)(*FUNCTION_TYPE)(parameter_type);
can help to make the declarations easier to write and possibly read.

The first argument "double (*fun)(double, double, double)" of the function randNormal is a function pointer. The below example will explain you the usage of the function pointer for some level. The code comment will explain in detail.
#include <iostream>
//Actual function 1
double fnGetMax(double a, double b, double c) {
//return someMathLibrary::StaticMaxOf(a, b ,c);
return a-b-c;
}
//Actual function 2
double fnGetMin(double a, double b, double c) {
//return someMathLibrary::StaticMinOf(a, b ,c);
return a+b+c;
}
//Actual function 3
//which takes the "function pointer" as argument of the actual functions like 1 & 2
double randNormal(double (*fun)(double, double, double), double xmin, double xmax, double sigma, double mju) {
static double (*Fun)(double, double, double) = NULL, YMin, YMax;
static bool First = true;
if (First) {
First = false;
srand((unsigned) time(NULL));
}
if (fun != Fun) {
Fun = fun;
//calling actual function 1 or 2
YMin = 0, YMax = Fun(xmin, sigma, mju);
} else {
//calling actual function 1 or 2
YMax = 0, YMin = Fun(xmax, sigma, mju);
}
return YMin + YMax;
}
int main(int argc, char** argv) {
//Creating function pointer for the actual function 1
double (*funMax_ptr)(double, double, double) = &fnGetMax;
//Creating function pointer for the actual function 2
double (*funMin_ptr)(double, double, double) = &fnGetMin;
//Passing the function pointer to the randNormal (actual function 3)
std::cout << randNormal(funMax_ptr,1.0,2.0,3.0,4.0) << std::endl;
std::cout << randNormal(funMin_ptr,1.0,2.0,3.0,4.0) << std::endl;
return 0;
}
Output:
-6
8

Related

Pass a function as argument, without knowlegde of number of arguments of this function [duplicate]

long time browser, first time asker here. I've written a number of scripts for doing various 1D numerical integration methods and compiled them into a library. I would like that library to be as flexible as possible regarding what it is capable of integrating.
Here I include an example: a very simple trapezoidal rule example where I pass a pointer to the function to be integrated.
// Numerically integrate (*f) from a to b
// using the trapezoidal rule.
double trap(double (*f)(double), double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += (*f)(xi); }
else { s += 2*(*f)(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works great for simple functions that only take one argument. Example:
double a = trap(sin,0,1);
However, sometimes I may want to integrate something that has more parameters, like a quadratic polynomial. In this example, the coefficients would be defined by the user before the integration. Example code:
// arbitrary quadratic polynomial
double quad(double A, double B, double C, double x) {
return (A*pow(x,2) + B*x + C);
}
Ideally, I would be able to do something like this to integrate it:
double b = trap(quad(1,2,3),0,1);
But clearly that doesn't work. I have gotten around this problem by defining a class that has the coefficients as members and the function of interest as a member function:
class Model {
double A,B,C;
public:
Model() { A = 0; B = 0; C = 0; }
Model(double x, double y, double z) { A = x; B = y; C = z; }
double func(double x) { return (A*pow(x,2)+B*x+C); }
};
However, then my integration function needs to change to take an object as input instead of a function pointer:
// Numerically integrate model.func from a to b
// using the trapezoidal rule.
double trap(Model poly, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += poly.func(xi); }
else { s += 2*poly.func(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works fine, but the resulting library is not very independent, since it needs the class Model to be defined somewhere. Also, ideally the Model should be able to change from user-to-user so I wouldn't want to fix it in a header file. I have tried to use function templates and functors to get this to work but it is not very independent since again, the template should be defined in a header file (unless you want to explicitly instantiate, which I don't).
So, to sum up: is there any way I can get my integration functions to accept arbitrary 1D functions with a variable number of input parameters while still remaining independent enough that they can be compiled into a stand-alone library? Thanks in advance for the suggestions.
What you need is templates and std::bind() (or its boost::bind() counterpart if you can't afford C++11). For instance, this is what your trap() function would become:
template<typename F>
double trap(F&& f, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi); }
// ^
else { s += 2* f(xi); }
// ^
}
s *= (b-a)/(2*N);
return s;
}
Notice, that we are generalizing from function pointers and allow any type of callable objects (including a C++11 lambda, for instance) to be passed in. Therefore, the syntax for invoking the user-provided function is not *f(param) (which only works for function pointers), but just f(param).
Concerning the flexibility, let's consider two hardcoded functions (and pretend them to be meaningful):
double foo(double x)
{
return x * 2;
}
double bar(double x, double y, double z, double t)
{
return x + y * (z - t);
}
You can now provide both the first function directly in input to trap(), or the result of binding the last three arguments of the second function to some particular value (you have free choice on which arguments to bind):
#include <functional>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
}
Of course, you can get even more flexibility with lambdas:
#include <functional>
#include <iostream>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
int x = 1729; // Or the result of some computation...
int y = 42; // Or some particular state information...
trap([&] (double d) -> double
{
x += 42 * d; // Or some meaningful computation...
y = 1; // Or some meaningful operation...
return x;
}, 0, 42);
std::cout << y; // Prints 1
}
And you can also pass your own stateful functors tp trap(), or some callable objects wrapped in an std::function object (or boost::function if you can't afford C++11). The choice is pretty wide.
Here is a live example.
What you trying to do is to make this possible
trap( quad, 1, 2, 3, 0, 1 );
With C++11 we have alias template and variadic template
template< typename... Ts >
using custom_function_t = double (*f) ( double, Ts... );
above define a custom_function_t that take a double and variable numbers of arguments.
so your trap function becomes
template< typename... Ts >
double trap( custom_function_t<Ts...> f, Ts... args, double a, double b ) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi, args...); }
else { s += 2*f(xi, args...); }
}
s *= (b-a)/(2*N);
return s;
}
Usage:
double foo ( double X ) {
return X;
}
double quad( double X, double A, double B, double C ) {
return(A*pow(x,2) + B*x + C);
}
int main() {
double result_foo = trap( foo, 0, 1 );
double result_quad = trap( quad, 1, 2, 3, 0, 1 ); // 1, 2, 3 == A, B, C respectively
}
Tested on Apple LLVM 4.2 compiler.

Integrate a function of three variables C++

I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.
I have a function !
double integrand(double r, double phi, double theta)
That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".
Algorithmically speaking what I wanted to do was :
double firstIntegral(double r, double phi) {
double result = integrationFunction(integrand,lower_bound,upper_bound);
return result;
}
And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.
How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?
This is a very slow and inexact version for integrals over cartesian coordinates, which should work with C++11.
It is using std::function and lambdas to implement the numerical integration. No steps have been taken to optimize this.
A template based solution could be much faster (by several orders of magnitude) than this, because it may allow the compiler to inline and simplify some of the code.
#include<functional>
#include<iostream>
static double integrand(double /*x*/, double y, double /*z*/)
{
return y;
}
double integrate_1d(std::function<double(double)> const &func, double lower, double upper)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower; x < upper; x+=increment) {
integral += func(x) * increment;
}
return integral;
}
double integrate_2d(std::function<double(double, double)> const &func, double lower1, double upper1, double lower2, double upper2)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower2; x < upper2; x+=increment) {
auto func_x = [=](double y){ return func(x, y);};
integral += integrate_1d(func_x, lower1, upper1) * increment;
}
return integral;
}
double integrate_3d(std::function<double(double, double, double)> const &func,
double lower1, double upper1,
double lower2, double upper2,
double lower3, double upper3)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower3; x < upper3; x+=increment) {
auto func_x = [=](double y, double z){ return func(x, y, z);};
integral += integrate_2d(func_x, lower1, upper1, lower2, upper2) * increment;
}
return integral;
}
int main()
{
double integral = integrate_3d(integrand, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
std::cout << "Triple integral: " << integral << std::endl;
return 0;
}
You can use functors
#include <iostream>
struct MyFunctorMultiply
{
double m_coeff;
MyFunctorMultiply(double coeff)
{
m_coeff = coeff;
}
double operator()(double value)
{
return m_coeff * value;
}
};
struct MyFunctorAdd
{
double m_a;
MyFunctorAdd(double a)
{
m_a = a;
}
double operator()(double value)
{
return m_a + value;
}
};
template<class t_functor>
double calculate(t_functor functor, double value, double other_param)
{
return functor(value) - other_param;
}
int main()
{
MyFunctorMultiply multiply2(2.);
MyFunctorAdd add3(3.);
double result_a = calculate(multiply2, 4, 1); // should obtain 4 * 2 - 1 = 7
double result_b = calculate(add3, 5, 6); // should obtain 5 + 3 - 6 = 2
std::cout << result_a << std::endl;
std::cout << result_b << std::endl;
}
If your concern is just about getting the right prototype to pass to the integration function, you can very well use alternative data passing mechanisms, the simpler of which is using global variables.
Assuming that the order of integration is on theta, then phi, then r, write three functions of a single argument:
It(theta) computes the integrand from the argument theta passed explicitly and the global phi and r.
Ip(phi) computes the bounds on theta from the argument phi passed explicitly and the global r; it also copies the phi argument to the global variable and invokes integrationFunction(It, lower_t, upper_t).
Ir(r) computes the bounds on phi from the argument r passed explicitly; it also copies the r argument to the global variable and invokes integrationFunction(Ip, lower_p, upper_p).
Now you are ready to call integrationFunction(Ir, lower_r, upper_r).
It may also be that integrationFunction supports a "context" argument where you can store what you want.

Changing the whole part of a number with the decimal part [duplicate]

I have a program in C++ (compiled using g++). I'm trying to apply two doubles as operands to the modulus function, but I get the following error:
error: invalid operands of types 'double' and 'double' to binary 'operator%'
Here's the code:
int main() {
double x = 6.3;
double y = 2;
double z = x % y;
}
The % operator is for integers. You're looking for the fmod() function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
fmod(x, y) is the function you use.
You can implement your own modulus function to do that for you:
double dmod(double x, double y) {
return x - (int)(x/y) * y;
}
Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.
Use fmod() from <cmath>. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

How to create a C++ array with variable elements?

I have this C++ program:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
double dx2(int t, int x, int dx)
{
return (-9.8*cos(x));
}
int square(int x)
{
return (x*x);
}
double RK4(float t, float x, float dx, float h)
{
double k1, k2, k3, k4, l1, l2, l3, l4, diff1, diff2;
k1 = h*dx2(t,x,dx);
l1 = h*k1;
k2 = h*dx2(t+h/2,x+l1/2,dx+k1/2);
l2 = h*k2;
k3 = h*dx2(t+h/2,x+l2/2,dx+k2/2);
l3 = h*k3;
k4 = h*dx2(t+h,x+l3,dx+k3);
l4 = h*k4;
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
double OUT[] = {diff1, diff2};
return OUT;
}
int main()
{
double diff, t, t0, t1, x, x0, dx, dx0, h, N;
N = 1000;
t0 = 0;
t = t0;
t1 = 10;
x0 = 0;
x = x0;
dx0 = 0;
dx = dx0;
h = (t1 - t0) / float(N);
for(int i = 1; i<=N; i++) {
diff = RK4(t,x,dx,h);
x = x + diff;
t = t + h;
}
cout << diff;
return 0;
}
As you can see in this program I am solving the 2nd-order differential equation (if there is a way to insert LaTeX equations into my question please tell me):
d2x/dt2= -9.8 cos(x)
which is an example of the simple pendulum's equations of motion. The problem lines are 33 and 34. In it I am attempting to define the first element of the OUT array as diff1 and the second element as diff2. Whenever I compile this program (named example.cpp) I get the error:
g++ -Wall -o "example" "example.cpp" (in directory: /home/fusion809/Documents/CodeLite/firstExample)
example.cpp: In function ‘double RK4(float, float, float, float)’:
example.cpp:33:9: error: cannot convert ‘double*’ to ‘double’ in return
return OUT;
^~~
Compilation failed.
Exactly, since you're returning an array of double's, that decays to double*, but the function is defined to return double. An array of type T and the type T are different types in C++, and they can't be converted between, generally speaking.
In this case, you might be better off with a std::pair<T1, T2> (#include <utility>) since you're using C++ and the standard library, or a structure with two fields of type double. Look up std::pair<> and std::tie<>, the former being used to make pairs of elements of different types, and the latter being used to make tuples of different types of arbitrary size.
When you write the std::pair's elements to std::cout, use the first, second members to access the pair's fields. A std::pair can't be directly output using the overloaded stream operator for std::cout.
Edit:
#include <utility>
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
/* snip */
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
return {diff1, diff2};
}
int main()
{
double x, dx;
/* snip */
for(int i = 1; i<=N; i++) {
std::pair<double, double> diff = RK4(t,x,dx,h);
// or use with C++11 and above for brevity
auto diff = RK4(t,x,dx,h);
x = x + diff.first;
dx = dx + diff.second;
t = t + h;
}
cout << x << " " << dx << "\n" ;
return 0;
}
The return type of your RK4 function is double, which is a single value, but you're trying to return an array of two of them. That won't work. You could change the return type to double* and use new double[2] to allocate an array, but it'd be simpler and safer to use std::pair<double, double> as the return type. Then you can just do return { diff1, diff2 };.
To return several values from function you have several choice:
as all you returned type are identical, you may return array:
std::array<double, 2> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
or std::vector
std::vector<double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
You may return std::tuple or std::pair (limited to 2 elements):
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
or
std::tuple<double, double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
You may also create a custom class
struct RK4Result
{
double diff1;
double diff2;
};
RK4Result RK4(float t, float x, float dx, float h)
{
// ...
return {diff1, diff2};
}
And for type expensive to move, you may use any previous method, but by out parameters:
struct RK4Result
{
double diff1;
double diff2;
};
void RK4(float t, float x, float dx, float h, RK4Result& res)
{
// ...
res = {diff1, diff2};
}

C++: pass function with arbitrary number of parameters as a parameter

long time browser, first time asker here. I've written a number of scripts for doing various 1D numerical integration methods and compiled them into a library. I would like that library to be as flexible as possible regarding what it is capable of integrating.
Here I include an example: a very simple trapezoidal rule example where I pass a pointer to the function to be integrated.
// Numerically integrate (*f) from a to b
// using the trapezoidal rule.
double trap(double (*f)(double), double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += (*f)(xi); }
else { s += 2*(*f)(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works great for simple functions that only take one argument. Example:
double a = trap(sin,0,1);
However, sometimes I may want to integrate something that has more parameters, like a quadratic polynomial. In this example, the coefficients would be defined by the user before the integration. Example code:
// arbitrary quadratic polynomial
double quad(double A, double B, double C, double x) {
return (A*pow(x,2) + B*x + C);
}
Ideally, I would be able to do something like this to integrate it:
double b = trap(quad(1,2,3),0,1);
But clearly that doesn't work. I have gotten around this problem by defining a class that has the coefficients as members and the function of interest as a member function:
class Model {
double A,B,C;
public:
Model() { A = 0; B = 0; C = 0; }
Model(double x, double y, double z) { A = x; B = y; C = z; }
double func(double x) { return (A*pow(x,2)+B*x+C); }
};
However, then my integration function needs to change to take an object as input instead of a function pointer:
// Numerically integrate model.func from a to b
// using the trapezoidal rule.
double trap(Model poly, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += poly.func(xi); }
else { s += 2*poly.func(xi); }
}
s *= (b-a)/(2*N);
return s;
}
This works fine, but the resulting library is not very independent, since it needs the class Model to be defined somewhere. Also, ideally the Model should be able to change from user-to-user so I wouldn't want to fix it in a header file. I have tried to use function templates and functors to get this to work but it is not very independent since again, the template should be defined in a header file (unless you want to explicitly instantiate, which I don't).
So, to sum up: is there any way I can get my integration functions to accept arbitrary 1D functions with a variable number of input parameters while still remaining independent enough that they can be compiled into a stand-alone library? Thanks in advance for the suggestions.
What you need is templates and std::bind() (or its boost::bind() counterpart if you can't afford C++11). For instance, this is what your trap() function would become:
template<typename F>
double trap(F&& f, double a, double b) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi); }
// ^
else { s += 2* f(xi); }
// ^
}
s *= (b-a)/(2*N);
return s;
}
Notice, that we are generalizing from function pointers and allow any type of callable objects (including a C++11 lambda, for instance) to be passed in. Therefore, the syntax for invoking the user-provided function is not *f(param) (which only works for function pointers), but just f(param).
Concerning the flexibility, let's consider two hardcoded functions (and pretend them to be meaningful):
double foo(double x)
{
return x * 2;
}
double bar(double x, double y, double z, double t)
{
return x + y * (z - t);
}
You can now provide both the first function directly in input to trap(), or the result of binding the last three arguments of the second function to some particular value (you have free choice on which arguments to bind):
#include <functional>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
}
Of course, you can get even more flexibility with lambdas:
#include <functional>
#include <iostream>
int main()
{
trap(foo, 0, 42);
trap(std::bind(bar, std::placeholders::_1, 42, 1729, 0), 0, 42);
int x = 1729; // Or the result of some computation...
int y = 42; // Or some particular state information...
trap([&] (double d) -> double
{
x += 42 * d; // Or some meaningful computation...
y = 1; // Or some meaningful operation...
return x;
}, 0, 42);
std::cout << y; // Prints 1
}
And you can also pass your own stateful functors tp trap(), or some callable objects wrapped in an std::function object (or boost::function if you can't afford C++11). The choice is pretty wide.
Here is a live example.
What you trying to do is to make this possible
trap( quad, 1, 2, 3, 0, 1 );
With C++11 we have alias template and variadic template
template< typename... Ts >
using custom_function_t = double (*f) ( double, Ts... );
above define a custom_function_t that take a double and variable numbers of arguments.
so your trap function becomes
template< typename... Ts >
double trap( custom_function_t<Ts...> f, Ts... args, double a, double b ) {
int N = 10000;
double step = (b-a)/N;
double s = 0;
for (int i=0; i<=N; i++) {
double xi = a + i*step;
if (i == 0 || i == N) { s += f(xi, args...); }
else { s += 2*f(xi, args...); }
}
s *= (b-a)/(2*N);
return s;
}
Usage:
double foo ( double X ) {
return X;
}
double quad( double X, double A, double B, double C ) {
return(A*pow(x,2) + B*x + C);
}
int main() {
double result_foo = trap( foo, 0, 1 );
double result_quad = trap( quad, 1, 2, 3, 0, 1 ); // 1, 2, 3 == A, B, C respectively
}
Tested on Apple LLVM 4.2 compiler.