我目前正在尝试将间隔切成不等宽的切片。实际上,我希望每个切片的宽度遵循对数规则。例如,第一个间隔应该大于第二个间隔,依此类推。
我很难记住我的数学讲座。因此,假设我知道a和b分别是间隔I的上下边界,而n是切片的数目:如何找到每个切片的上下边界(遵循对数刻度)?
换句话说,这是我为获得等宽间隔所做的事情:
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)
}
其中:p-1 =切片数,size_piece = | ba | 。
我现在想要获得的是开始值和结束值,但是遵循对数刻度而不是算术刻度(这将在for循环的某些函数中调用)。
在此先感谢您的帮助。
如果我理解您的问题,那么此C ++程序将为您展示可以使用的算法的实际示例:
#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;
}
输出(切片的极值)为:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句