How do I ensure a number is within a range? - c++

Suppose I have some value:
double x;
and I want to confine it to some range [a, b] such that the resulting value is within that range:
double confine(double x, double a, double b)
{
if (x < a) return a;
else if (x > b) return b;
return x;
}
Is there a single boost or STL function that can do this for me?

Yes, Boost Algorithm has clamp:
double clamped = clamp(x, a, b);
It requires only operator< or a custom comparator, and guarantees that it is called only once or twice. The documentation points out that with double and other floating-point types, NaN could cause unexpected results.

Apart from clamp(), you could also do this using a one liner in std::max() and std::min().
double confine(double x, double a, double b) {
return std::max(a, std::min(x, b));
}

Related

C++ trick to calling an overloaded function by it's number of parameters based on a class template

I have to build an interface HistoWapper that aggregates a histogram class that has three methods which vary by their parameter count, which I have to call
class Histogram {
...
double Interpolate(double X);
double Interpolate(double X, double Y);
double Interpolate(double X, double Y, double Z);
...
};
Right now I'm doing a switch on the dimension of my histogram and selecting the correct implementation at runtime.
class HistoWrapper {
...
Histogram hist_;
int dimension;
double x_;
double y_;
double z_;
double getValue() {
if(dimension == 1)
return hist_.getValue(x_);
else if(dimension == 2)
return hist_.getValue(x_, y_);
else if(dimension == 3)
return hist_.getValue(x_, y_, z_);
}
...
};
This code has many problems. When the dimension is 1, y_ and z_ are unused variables which take up memory for nothing. And getValue() will be called for millions of values at runtime meaning the branching will be very expensive and inneficient with big data.
The dimension of the histogram is known at compile time.
I'm wondering how I could avoid to do this else if ? Perhaps C++17 constexpr could be used on the dimension with an int using non type template parameters ? Could variadic templates be a solution here too ?

How should I use automatic type conversion in the sum of two complex numbers? (C++)

I've created a class Complex for a complex number and the get/set methods to extract and change the real and imaginary part of the number. Now I want to sum and multiplicate two complex numbers, so I've created the following functions:
Complex somma(Complex a, Complex b) {
Complex c;
c.set_Rez(a.get_Rez()+b.get_Rez());
c.set_Imz(a.get_Imz()+b.get_Imz());
return c;
}
Complex prodotto(Complex a, Complex b) {
Complex c;
c.set_ro(a.get_ro()*b.get_ro());
c.set_fi(a.get_fi()+b.get_fi());
return c;
}
My question is if there is a way to have as an output of the functions a simple double if the inputs are doubles. Is it possible to give to the functions doubles and getting a double as a result?
My question is if there is a way to have as an output of the functions a simple double if the inputs are doubles. Is it possible to give to the functions doubles and getting a double as a result?
It sounds like you want the following overloads:
Complex somma(Complex a, Complex b);
Complex somma(Complex a, double b);
Complex somma(double a, Complex b);
double somma(double a, double b);
If there is converting constructor from a double to a Complex, you can simply use:
Complex somma(Complex a, Complex b);
double somma(double a, double b);
to get what you need. You need similar functions for prodotto
Complex prodotto(Complex a, Complex b);
double prodotto(double a, double b);
Overloading the functions somma and prodotto for Complex and double makes your code look more uniform. However, it will more idiomatic to overload operator+ and operator* for Complex.
Complex operator+(Complex const& lhs, Complex const& rhs) { ... }
Complex operator*(Complex const& lhs, Complex const& rhs) { ... }
Then you can use
Complex c1 = { ... };
Complex c2 = { ... };
Complex c3 = c1 + c2;
Complex c4 = c1 * c2;
Then, you don't have to worry about overloading somma and prodotto for double. You can just use + and * for objects of type Complex as well as type double.

Replace function pointers by templates in C++11

I have a script (python symbolic toolbox) which auto-generates C++11 code to fill the entries of a matrix, like:
double J00(double a, double b) {return a+b;}
double J01(double a, double b) {return a-b;}
double J10(double a, double b) {return -a+b;}
double J11(double a, double b) {return -a-b;}
Now I could use an array of function pointers to store all the functions and fill the matrix, i.e.:
typedef double (*FillFunction) (double a, double b);
double J00(double a, double b) {return a+b;}
double J01(double a, double b) {return a-b;}
double J10(double a, double b) {return -a+b;}
double J11(double a, double b) {return -a-b;}
void main()
{
FillFunction J[2][2] = {{J00, J01}, {J10, J11}};
param0 = 0;
param1 = 1;
double Jresult[2][2];
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
Jresult[i][j] = J[i][j](param0, param1);
}
}
}
However, this is a performance critical part of my code and I would thus rather not use function pointers, especially since the size of the matrix and all functions are know at compile time. Is there a neat way to do this with templates or anything similar?
Note: I did not compile this code so I don't know if it would actually work, but I hope you get the idea.
If you are using external code generator anyway, just generate this:
double Jresult[2][2] = {
{J00(param0, param1), J01(param0, param1)},
{J10(param0, param1), J11(param0, param1)},
};

What this declaration "float (*x[20])(int *a)" means?

I found somewhere this weird variable declaration -
float (*x[20])(int *a);
What could it possibly mean?
What is the purpose of it?
float (*x[20])(*int a) is not correct. It should be float (*x[20])(int *a) which declares x as an array of 20 pointers to a function that takes an argument of int * type and returns float.
For those who are curious to know the use of an array of function pointers:
typedef double Func(double, double); // Declare a double (double, double)
Func sum, subtract, mul, divide; // Function prototypes.
Func *p[] = { sum, subtract, mul, divide }; // Array of function pointers
int main(void)
{
double result;
double a, b;
int option;
printf("This is a simple calculator to add, subtract, multiply and divideide two integers\n");
printf("Enter two integers: ");
scanf("%lf %lf", &a, &b);
printf("Choose an option:\n 1. Add\n 2. Subtract\n 3. Mult\n 4. Divide\n");
scanf("%d", &option);
result = p[option - 1](a, b);
printf("result = %lf\n", result);
}
double sum(double a, double b) { return a+b; }
double subtract(double a, double b) { return a-b; }
double mul(double a, double b) { return a*b; }
double divide(double a, double b) { return a/b; }
A detailed explanation on how to read/decipher such complex declaration is discussed here.
this is an array of function pointers. it has 20 function pointer items.
The declaration
float (*x[20])(int *a);
defines the variable x as an array of 20 functions (function pointers). In my humble opinion it's more clearly written as
Function x[20];
with
typedef float (*Function)(int *a);
The purpose of x is hard to tell without context, it could be to compute a statistical value like average, variance or standard deviation etc. given a set of integers and a function index input by the user:
x[0] = Average;
x[1] = Variance;
x[2] = StandardDeviation;
...
int a[100];
int i;
/*read data into `a' and function index into i...*/
printf("%f\n", x[i](a));
The code should be like this: - float (*x[20])(int *a); - as (*int a) seems to be incorrect. The code tells me that x is an array of 20 pointers to function that each takes an argument with datatype int and return float.

Invalid cast from Complex* to double

I have to return the distance between two complex numbers and the error I get is in the return line saying "Invalid cast from Complex* to double".
double Complex::distance(const Complex &a, const Complex &b)
{
Complex *number = new Complex();
number->modificaRe(a.real() - b.real());
number->modificaIm(a.imag() - b.imag());
return (double)number;
}
Could you please tell me what is it that I'm doing wrong?
Not to mention that the teacher gave us the definition of this function as "static double" but I was getting another error so I just removed "static".
The problem is that a double cannot carry both the real and imaginary parts of the Complex.
I believe that the distance between two complex numbers is the sqrt of the sum of the square of the differences.
So, you code should be...
double Complex::distance(const Complex &a, const Complex &b)
{
double number;
double r = a.real() - b.real();
double i = a.imag() - b.imag();
number = sqrt(r*r + i*i);
return number;
}
As H2CO3 points out it may be safter to use std::hypot...so
double Complex::distance(const Complex &a, const Complex &b)
{
return std::hypot(a.real() - b.real(), a.imag() - b.imag());
}
If I remember correctly the distance can be calculated using pythagorus - so creating the
Complex object in distance() is not necessary.
double Complex::distance(const Complex &a, const Complex &b)
{
double x = a.real() - b.real();
double y = a.imag() - b.imag();
return sqrt(x * x + y * y);
}
The easiest solution would be to use the standard library's std::comlpex class template. You can use subtraction and std::abs to get the "distance":
#include <complex>
#include <iostream>
template <typename T>
T complex_distance(const std::complex<T>& a, const std::complex<T>& b)
{
return std::abs(b-a);
}
int main()
{
std::complex<double> c1(-1,-1);
std::complex<double> c2(2,2);
std::cout << (c2-c1) << std::endl;
std::cout << complex_distance(c2,c1) << std::endl;
}
Casting from a pointer to a Complex to a double is not supported. It's not even clear why you're creating a pointer here rather than just allocating it on the stack.
For example:
double Complex::distance(const Complex &a, const Complex &b)
{
Complex number;
number.modificaRe(a.real() - b.real());
number.modificaIm(a.imag() - b.imag());
return (double)number;
}