Any way to keep the internal common in macros? - c++

For example, I have a simple macro
#define MIN(a, b) (a) < (b) ? (a) : (b)
and I want to use
MIN(pow(2, 3) , 10);
The internal common gives trouble. I can do as following
int a = pow(2, 3);
MIN(a, 10);
I am looking for a better way that is more readable by like keeping pow(2, 3) in the macro? Is it possible? Thanks!

You can use std::min instead:
#include <algorithm>
//...
double x = std::min(pow(2, 3) , 10);
Generally, you should prefer an inline function over a macro. If the purpose of the macro is to allow it to work for a variety of types, you can use a template.
template <typename T>
inline T SomeFunction (T x, T y) {
T result;
//...do something with x and y and assign to result
return result;
}

Related

When to use std::numeric_limits<double>::espsilon() instead of DBL_EPSILON

I understood that std::numeric_limits::espsilon() and DBL_EPSILON should deliver the same value but are defined in different headers, limits, and cfloat. Which makes std::numeric_limits::espsilon() a c++ style way of writing and DBL_EPSILON the c style.
My question is if there is any benefit in using std::numeric_limits::espsilon() over DBL_EPSILON in c++ project? Aside from a clean c++ coding style. Or did I understand this completely wrong?
Here on this page https://en.cppreference.com/w/cpp/types/numeric_limits you can find tables of what are the C marco equivalents of the std::numeric_limits.
They are equivalents, so for any pair of std::limits function/constant and C macro you find in the table, they can be interchanged.
The big difference is in generic code:
template <typename T>
void foo() {
std::cout << std::numeric_limits<T>::epsilon();
}
Doing the same with C macros would require to write much more code. Also any opportunity to not use a macro is a good one.
First of all DBL_EPSILON is a C API so it is a good practice to use C++ specific API in C++ code. I know it is more typing, still it is a good practice. In my code when I need epsilon multiple times for single type, I just bind it to some constexpr.
More important thing this is a great tool when you write a template. For example:
template<std::floating_point T>
bool fuzzyCompare(T a, T b)
{
return std::fabs(a - b) <= 4 * std::max(std::fabs(a), std::fabs(b)) * std::numeric_limits<T>::espsilon();
}
One obvious advantage of using std::numeric_limits<T>::epsilon is generic function. Imagine if you write some function like an almost-equal. This function should accept floating numbers of different precisions, including double, float, long double. Or maybe even integer types as well. To write this with the macro solution, you would have to write an overload for each of the floating point types:
bool almost_equal(float a, float b, int k)
{
return std::abs(a - b) <= FLT_EPSILON * std::abs(a + b) * k;
}
bool almost_equal(double a, double b, int k)
{
return std::abs(a - b) <= DBL_EPSILON * std::abs(a + b) * k;
}
...
But with the numeric_limits template, you can simply write a single function for all of them:
template<typename T>
bool almost_equal(T a, T b, int k)
{
return std::abs(a - b) <= std::numeric_limits<T>::epsilon() * std::abs(a + b) * k;
}

Is there an easier way to write conditional statements with NumericVector in Rcpp?

I am trying to write up some code using Rcpp, and I'm trying to get the hang of how conditional statements work between logical vectors as they arise from comparisons using NumericVector, and C++'s native bool type.
The method that I've settled on is as follows (minimal reproducible example, my example was more complicated):
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector compare(NumericVector a, NumericVector b) {
if (is_true(all(b <= a))) {
return a;
}
return b;
}
However the is_true and all seem redundant if (for instance as in my more complicated case that I am not showing you), a and b are guaranteed to be of length 1.
Now did I just find a ridiculously convoluted technique, or is this an unfortunate case of 'this is the best we've got (and the reasons for this approach are better than the reasons against, despite edge cases like this)'?
Unfortunately, is_true() and is_false() are required for use with all() Rcpp sugar function because:
The actual return type of all(X) is an instance of the SingleLogicalResult template class, but the functions is_true and is_false may be used to convert the return value to bool.
c.f. http://thecoatlessprofessor.com/programming/unofficial-rcpp-api-documentation/#all
The only way around this is to implement the loop yourself (hinted at by #Aconcagua):
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector compare_loop(Rcpp::NumericVector a, Rcpp::NumericVector b) {
if(a.size() != b.size()) Rcpp::stop("Lengths of a and b must be the same.");
for (int i = 0; i < a.size(); ++i) {
// take opposite of comparison or switch it to b[i] > a[i]
if ( !(b[i] <= a[i]) ) {
return b;
}
}
return a;
}
Test:
a = c(-1, 2, 3, 5)
b = c(-3, -2, 4, 3)
all.equal(compare_loop(a,b), compare(a,b))
# [1] TRUE

Pass #define content as parameter

I have a long algorithm that should process some instruction described from more than one #define in order to reduce drastically my source-code. For example:
#define LongFunction(x, y, alg) return alg(x, y)
#define Alg1(x, y) ((x)+(y))
#define Alg2(x, y) ((x)^((x)-(y)))
And all I need to do is
LongFunction(x, y, Alg1);
LongFunction(x, y, Alg2);
I'd like to not pass a function as parameter because LongFunction is full of loops and I want that the code will be as fast as possible. How can I accomplish this task smartly?
There are many ways to parameterize on function.
Using macros might seem simple, but macros don't respect scopes, and there are problems with parameter substitution and side-effects, so they're Evil™.
In C++11 and later the most natural alternative is to use std::function and lambdas, like this:
#include <functional> // std::function
#include <math.h> // pow
using std::function;
auto long_function(
double const x,
double const y,
function<auto(double, double) -> double> alg
)
-> double
{
// Whatever.
return alg( x, y ); // Combined with earlier results.
}
auto alg1(double const x, double const y)
-> double
{ return x + y; }
auto alg2(double const x, double const y)
-> double
{ return pow( x, x - y ); }
#include <iostream>
using namespace std;
auto main() -> int
{
cout << long_function( 3, 5, alg1 ) << endl;
}
Regarding “fast as possible”, with a modern compiler the macro code is not likely to be faster. But since this is important, do measure. Only measurements, for release build and in the typical execution environment, can tell you what's fastest and whether the speed is relevant to the end user.
Of old, and formally, you could use the inline specifier to hint to the compiler that it should machine code inline calls to a function. Modern compilers are likely to just ignore inline for this (it has another more guaranteed meaning wrt. ODR). But it probably won't hurt to apply it. Again, it's important to measure. And note that results can vary with compilers.
One alternative to the above is to pass a simple function pointer. That might be faster than std::function, but is less general. However, in the other direction, you can templatize on a type, with a member function, and that gives the compiler more information, more opportunity to inline, at the cost of not being able to e.g. select operations from array at runtime. I believe that when you measure, if this is important enough, you'll find that templatization yields fastest code. Or at least as fast as the above.
Example of templatizing on a type that provides the operation:
#include <math.h> // pow
template< class Op >
auto long_function( double const x, double const y )
-> double
{
// Whatever.
return Op()( x, y ); // Combined with earlier results.
}
struct Alg1
{
auto operator()(double const x, double const y)
-> double
{ return x + y; }
};
struct Alg2
{
auto operator()(double const x, double const y)
-> double
{ return pow( x, x - y ); }
};
#include <iostream>
using namespace std;
auto main() -> int
{
cout << long_function<Alg1>( 3, 5 ) << endl;
}
By the way, note that ^ is not an exponentiation operator in C++ (it is in e.g. Visual Basic). In C and C++ it's a bitlevel XOR operator. In the code above I've assumed that you really meant exponentiation, and used the pow function from <math.h>.
If, instead, you really meant bitlevel XOR, then the arguments would need to be integers (preferably unsigned integers), which then would indicate that you want argument types for long_function depending on the argument types for the specified operation. That's more thorny issue, but involves either overloading or templating, or both. If that's what you really want then please do elaborate on that.

C++: newton raphson and overloading functions

I wrote a simple implementation of the newton raphson root finding algorithm which takes an initial guess init, a unary function f and the tolerance tol as arguments, as shown below:
bool newton_raphson(double& init,
double(*f)(double),
double tol){
const int max_iter = 10000;
double next_x, soln = init;
int i = 0;
while(++i < max_iter){
next_x = soln - f(soln)/fp_x(f, soln);
if(fabs(next_x - soln) < tol){
init = next_x;
return true;
}
soln = next_x;
}
return false;
}
double fp_x(double(*f)(double),
double x){
const double h = 0.000001;
return (f(x + h) - f(x - h))/2.0/h;
}
My question is: although this works perfectly fine for unary functions, I would like to change the implementation so that it works for functions f that have more than one parameter, but all except one parameter have constant values. To clarify: if I have a function f(x) = 3x + 2 as shown below
double f(double x){
return (3*x + 2);
}
Then my implementation works. However, I would also like it to work for any functions with any given number of arguments, but only the first argument is variable. So, if I have a function f(x,y) = 3x + 2y
double f(double x, double y){
return (3*x + 2*y);
}
I would like to find the root of f(x,2), or f(x,3) using the same function, and so on for n arguments, not just one or two (please ignore the idea that the functions I showed in the example are simple linear functions, this is just an example). Is there any way to implement the function for a varying number of arguments or do I have to write an implementation for every case?
Thanks,
NAX
NOTE
As you could tell by now, this question isn't really about newton-raphson, but it makes it easier if I use it as an example for the actual question, which is a single implementation for functions of different numbers of arguments.
UPDATE
A few answers below use std::bind and std::function to solve the problem, which actually better address my question than the selected answer; however, they are c++11 library classes/functions, (which, don't get me wrong, is something I strongly urge every c++ programmer to go ahead and learn) and at the time of this writing, I was facing some problems using them; Eclipse Juno using g++ 4.7 (which is c++11 compliant) still somehow failed to recognize std::function, and I therefore decided to go and stick with the checked answer below, which also works nicely.
I think you're asking for variadic functions:
A variadic function – a function declared with a parameter list ending
with ellipsis (...) – can accept a varying number of arguments of
differing types. Variadic functions are flexible, but they are also
hazardous. The compiler can't verify that a given call to a variadic
function passes an appropriate number of arguments or that those
arguments have appropriate types. Consequently, a runtime call to a
variadic function that passes inappropriate arguments yields undefined
behavior. Such undefined behavior could be exploited to run arbitrary
code.
From here:
https://www.securecoding.cert.org/confluence/display/cplusplus/DCL31-CPP.+Do+not+define+variadic+functions
However, as quoted above, there are a number of problems with them.
Most notably, it only works for compile time!
However, if you are interested in implementing one, here's an article with a nice example:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=138
UPDATE:
IMO, I think you're better off defining functions that take structure or object arguments (i.e. a general function object), and writing functions that work on those arguments explicitly.
The other option is to do some compile-time reflection - which would be useful, but is too much trouble to do in such an example as this. Plus, "reflection" in C++ isn't "true" reflection, but rather a bad and incomplete implementation of it.
For what you're trying to do here, what you're looking for is std::bind (or, if you're dealing with a C++03 compiler, std::bind1st and std::bnd2nd).
These will let you "bind" values to the other parameters, leaving you with a function (technically, a function object) that only requires a single parameter.
What you'd ideally like would be something like this:
double f(double x, double y) {
return 3*x + 2*y;
}
double init = 1.0;
newton_raphson(init, std::bind2nd(f, 3), 1e-4);
Unfortunately, in real use, it's not quite that simple -- to work with std::bind2nd, you can't use an actual function; you need to use a function object instead, and it has to derive from std::binary_function.
std::bind is quite a bit more flexible, so that's what you almost certainly want to use instead (if at all possible).
I used your question as a way to force myself to learn C++11 variadic template, here is a working example.
template< typename... Ts >
double f( Ts... Vs ) {
double array[] = { Vs... };
int numArg = sizeof...( Vs );
switch (numArg) {
case 1:
return 3 * array[0] + 2;
case 2:
return 3 * array[0] + 2 * array[1];
case 3:
return 3 * array[0] + 2 * array[1] + 1 * array[3];
....
default:
return 0.0;
}
}
template< typename... Ts >
double newton_raphson( double &init, double tol,
double (*func) ( Ts... Vs ), Ts... Vs ) {
return func( Vs... );
}
you can call it like
newton_raphson( &init, 1.0, f, 1.0, 2.0, 3.0, 4.0, 5.0 );
You can use std::bind and std::function. The type std::function<double(double)> represents a functional that takes in a double and returns a double. Similarly std::function<double(int,int)> is for a functional taking 2 ints and returns a double.
#include <functional>
bool newton_raphson(double& init,
std::function<double(double)>& f,
double tol){
const int max_iter = 10000;
double next_x, soln = init;
int i = 0;
while(++i < max_iter){
next_x = soln - f(soln)/fp_x(f, soln);
if(fabs(next_x - soln) < tol){
init = next_x;
return true;
}
soln = next_x;
}
return false;
}
double myfunction(double x, double y){
return (3*x + 2*y);
}
double fp_x(std::function<double(double)> f, double x) {
...
}
...
double d = 1.0;
// Here we set y=2.5 and we tell bind that 1st parameter is unbounded
// If we wanted to switch and set x=2.5 and let y be unbounded, then
// we would use (&myfunction, 2.5, std::placeholders::_1)
newton_raphson(d, std::bind(&myfunction, std::placeholders::_1, 2.5) , 1e-6);
...

C++ : Strange metafunction call

I have a strange metafunction behavior in my C++ code and I want to understand why.
#include <iostream>
#include <cmath>
inline double f(double x, double y)
{
std::cout<<"Marker"<<std::endl;
return sqrt(x*y);
}
template <int N, class T> inline T metaPow(T x)
{
return ((N > 0) ? (x*metaPow<((N > 0) ? (N-1) : (0))>(x)) : (1.));
}
int main()
{
double x;
double y;
std::cin>>x;
std::cin>>y;
std::cout<<metaPow<5>(f(x, y))<<std::endl;
return 0;
}
I expected that the line metaPow<5>(f(x, y)) was equivalent to f(x, y)*f(x, y)*f(x, y)*f(x, y)*f(x, y)*1.. But if it was, it would print me five times the "Marker" line in the f function.
The strange thing is that I have the good result at the end (for example 181.019 for x = 2 and y = 4) but I have only 1 "Marker" displayed. How is it possible ? And consequently is it a good option to use that function for compile-time optimization instead of the standard pow() ?
Thank you very much !
I believe that f(x,y) is being evaluated before being passed in to your metaPow function. So the x argument to metaPow is just the value sqrt*(8). metaPow is never calling f(x,y). Hence, f(x,y) is only called once - when you initially call metaPow in your main function.
I think:
metaPow<5>(f(x, y))
equals to
double z = f(x, y); metaPow<5>(z);