These Python Functions In C++?
Solution 1:
If you're trying to convert the code to C++, you can easily implement a (roughly) equivalent arange
function:
#include<vector>template<typename T>
std::vector<T> arange(T start, T stop, T step = 1){
std::vector<T> values;
for (T value = start; value < stop; value += step)
values.push_back(value);
return values;
}
You could then use it like this:
auto t = arange<double>(0, 3*fs);
auto L = t.length();
The **
is exponentiation. You could call the pow
function:
#include<cmath>constdouble imax = pow(2., 16.);
But since you are dealing with constants anyway, you would be better off with:
constdouble imax = 65536.;
If you want to retain the expressive power of 2**16
and you don't want to incur the run-time cost of calling pow
(perhaps you want to be able to change the exponent without having to manually recalculate the constant), you can use a constexpr
function:
constexprunsignedlongpower(unsignedlong base, unsignedlong exponent){
return exponent == 0 ? 1 : base * pow(base, exponent - 1);
}
constunsignedlong imax = power(2, 16);
Solution 2:
Here is an explanation for all the non-trivials lines you outlined:
len(t)
means "length oft
", that is to say, the number of elements in array t.2**16
is "two to the power of 16" (1 << 16
in your C++ code).for n in range(0,L)
is equivalent tofor (int n = 0; i < L; ++i)
arange
andzeros
are likely Numpy functions. You can find reference for them here and here.
Regarding the last point, probably there is some import
statement you omitted from the code.
Quoting from the docs:
arange
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop).
The default step is 1
, so t
will be an array containing numbers [0, 1, 2, 3, ..., 3 * 44100 - 1]
.
zeros
Return a new array of given shape and type, filled with zeros.
Default type for zeros
is float
, so s
, sd1
and sd2
are initialized as arrays filled of 0.0
, each having L
elements.
Solution 3:
Python: t = arange(0,3*fs)
C++: double t[] = {0.0,1.0,...,3*fs}; // will not compile of course
Python: L = len(t)
C++: int L = sizeof(t)/sizeof(*t); // where t is an array in the current scope
Python: s = zeros(L)
C++: double s[L] = {0}; // where L is a constant
Python: for n in range(0,L)
C++: for (int i=0; i<L; i++)
Post a Comment for "These Python Functions In C++?"