How to get a logarithmic distribution from an interval

百般思念 提交于 2019-12-07 18:57:56

问题


I am currently trying to cut an interval into not equal-width slices. In fact I want the width of each slice to follow a logarithmic rule. For instance the first interval is supposed to be bigger than the second one, etc.

I have a hard time remembering my mathematics lectures. So assuming I know a and b which are respectively the lower and upper boundaries of my interval I, and n is the number of slices: how can I find the lower and upper boundaries of each slice (following a logarithmic scale)?

In other word, here's what I have done to get equal-width interval:

for (i = 1; i< p; i++) {
    start = lower + i -1 + ((i-1) * size_piece);

    if (i == p-1 ) {
      end = upper;
    } else {  
      end = start + size_piece;
    }
    //function(start, end)
  }

Where: p-1= number of slices, and size_piece = |b-a|.

What I want to get now is start and end values, but following a logarithmic scale instead of an arithmetic scale (which are going to be called in some function in the for loop).

Thanks in advance for your help.


回答1:


If I have understood your question, this C++ program will show you a practical example of the algorithm that can be used:

#include <iostream>
#include <cmath>

void my_function( double a, double b ) {
    // print out the lower and upper bounds of the slice
    std::cout << a << " -- " << b << '\n';
}

int main() {

    double start = 0.0, end = 1.0;
    int n_slices = 7;

    // I want to create 7 slices in a segment of length = end - start
    // whose extremes are logarithmically distributed:
    //     |         1       |     2    |   3  |  4 | 5 |6 |7|
    //     +-----------------+----------+------+----+---+--+-+
    //   start                                              end

    double scale = (end - start) / log(1.0 + n_slices);
    double lower_bound = start;
    for ( int i = 0; i < n_slices; ++i ) {
        // transform to the interval (1,n_slices+1):
        //     1                 2          3      4    5   6  7 8
        //     +-----------------+----------+------+----+---+--+-+
        //   start                                              end

        double upper_bound = start + log(2.0 + i) * scale;

        // use the extremes in your function
        my_function(lower_bound,upper_bound);

        // update
        lower_bound = upper_bound;
    }

    return 0;
}

The output (the extremes of the slices) is:

0 -- 0.333333
0.333333 -- 0.528321
0.528321 -- 0.666667
0.666667 -- 0.773976
0.773976 -- 0.861654
0.861654 -- 0.935785
0.935785 -- 1


来源:https://stackoverflow.com/questions/35585913/how-to-get-a-logarithmic-distribution-from-an-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!