Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating set of "N" numbers in an integer range at "logarithmic" distance in C++

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.

like image 673
usman Avatar asked Dec 15 '22 08:12

usman


2 Answers

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.

like image 71
ltjax Avatar answered May 15 '23 01:05

ltjax


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]);
}
like image 39
fatihk Avatar answered May 15 '23 02:05

fatihk