I couldn't find exact answer to this question so I am posting it here: If I have an integer range, I want to calculate "N" numbers in this range at equal logarithmic distance.
Here is a sample code to find numbers at equal "non-logarithmic" distance (more or less):
const int N = 100; // total no of sizes to generate
const int LOW = 10; // range low-bound
const int HIGH = 1000000; // range upper-bound
int SIZES[N];
int GAP = (HIGH-LOW)/N;
SIZES[0] = LOW + GAP;
for(int i=1; i<N; ++i)
{
SIZES[i] = SIZES[i-1] + GAP;
}
However, I want to find "N" numbers in this range at "logarithmic" distance.
I can only guess what you really want is a logarithmic scale.
In that case, instead of adding a constant GAP
, you multiply by a constant FACTOR
.
The FACTOR can be found by solving the equation LOW*FACTOR^N=HIGH
for FACTOR
.
It turns out the solution is the N'th root of HIGH/LOW.
You can use log
and exp
functions for this purpose. To avoid rounding problems, operating on double
data type can be a better choice.
Function log
gives natural logarithm but using any other base other than number e
(like log10() ) will also give same results because there is only one unique set of numbers with equal logarithmic distance for a given interval:
#include <math.h> /* log & exp & round */
const double N = 100; // total no of sizes to generate
const double LOW = 10; // range low-bound
const double HIGH = 1000000; // range upper-bound
double SIZES[N];
double GAP = (log(HIGH)-log(LOW))/N;
SIZES[0] = LOW*exp(GAP);
for(int i=1; i<N; ++i)
{
SIZES[i] = (SIZES[i-1]*exp(GAP));
}
//rounding
for(int i=1; i<N; ++i)
{
SIZES[i] = round(SIZES[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With