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

I could not find the exact answer to this question, so I post it here: If I have an integer range, I want to calculate the numbers "N" in this range at an equal logarithmic distance.

Here is an example code for finding numbers at an 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 the numbers "N" in this range at a "logarithmic" distance.

+4
source share
2 answers

For this purpose you can use the log and exp functions. To avoid rounding issues, it is best to use a double data type.

The log function gives the natural logarithm, but using any other base other than the number e (for example, log10 ()) will also give the 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]); } 
+2
source

I can only guess what you really want, this is a logarithmic scale.

In this case, instead of adding the GAP constant, you multiply by the FACTOR constant. A FACTOR can be found by solving the equation LOW*FACTOR^N=HIGH for FACTOR .

It turns out that the solution is the Nth root of HIGH / LOW.

+10
source

Source: https://habr.com/ru/post/1491631/


All Articles