在C ++中有类似numpy.logspace的东西吗?

时间:2014-01-29 11:10:11

标签: c++

正如标题所说,我正在寻找一些生成日志空间值的函数,就像numpy.logspace那样,但对于python。和想法?

2 个答案:

答案 0 :(得分:3)

标准库中没有这样的功能,但是,您可以轻松编写自己的功能。由于C ++和Python的不同性质,该功能不会完全相同。我建议使用生成器样式的函数对象:

template<typename T>
class Logspace {
private:
    T curValue, base;

public:
    Logspace(T first, T base) : curValue(first), base(base) {}

    T operator()() {
        T retval = curValue;
        curValue *= base;
        return retval;
    }
};

示例用法(以1开头的基数为2的40个值):

std::vector<double> vals;
std::generate_n(std::back_inserter(vals), 40, Logspace<double>(1,2));

评论的示例解决方案:

std::vector<double> pyLogspace(double start, double stop, int num = 50, double base = 10) {
    double realStart = pow(base, start);
    double realBase = pow(base, (stop-start)/num);

    std::vector<double> retval;
    retval.reserve(num);
    std::generate_n(std::back_inserter(retval), num, Logspace<double>(realStart,realBase));
    return retval;
}

generate_while

的示例实现
template<typename Value, typename OutputIt, typename Condition, typename Generator>
void generate_while(OutputIt output, Condition cond, Generator g) {
    Value val;
    while(cond(val = g())) {
        *output++ = val;
    }
}

答案 1 :(得分:0)

好吧我认为Erbureth代码是错误的,但是从他提供的代码片段中获取正确的代码真的很容易。下面是生成器+用法示例。

Logspace接受numpy.linspace之类的参数,并生成相同的序列。它可以超越它。但第一个值是相同的。它的工作方式就像endpoint设置为True

#include<iostream>
#include<cmath> 

//for generator
#include<vector>
#include<algorithm>
#include<iterator>

template<typename T = double>
class Logspace {
private:
    T curValue, base, step;

public:
    Logspace(T first, T last, int num, T base = 10.0) : curValue(first), base(base){
       step = (last - first)/(num-1);
    }

    T operator()() {
        T retval = pow(base, curValue);
        curValue += step;
        return retval;
    }
};



int main(){
 int num = 4;
 Logspace<> generator(2, 3, 4, 2);
 for(int i = 0; i < num; ++i) std::cout << generator() << '\n';

 //
 std::cout << "1 to million\n";
 double start = 1;
 double stop = 6;
 num = 40;
 std::vector<double> vals;
 std::generate_n(std::back_inserter(vals), num, Logspace<>(start,stop,num));
 for(double num : vals) std::cout << num << '\n';

 return 0;
}