2017-03-06 60 views
1

在Python我可以c + +升压的Python numpy的数组初始化

import numpy as np 
... 
foo = np.array([np.NINF] * x) 

其中x是int例如初始化负INF的x长度numpy的阵列42.我想用Boost.Python在C++中做同样的事情。以下显然不会工作:

namespace bnp = boost::python::numpy; 
... 
bnp::ndarray foo = bnp::array({-INFINITY} * x); 

有什么好办法做到这一点?我知道Boost.Numpy docs and tutorial - 他们不是很棒。

更一般地说,我如何初始化std向量或长度为x的数组的值为-INFINITY?

UPDATE:

我试图验证方法(使用初始环路在评论中所建议的),然后通过打印到控制台

for (auto i=0; i<x; ++i) { 
    std::cout << foo[i] << '\n'; 
} 

但出现以下错误: error: use of overloaded operator '<<' is ambiguous (with operand types 'ostream' (aka 'basic_ostream<char>') and 'object_item' (aka 'proxy<boost::python::api::item_policies>'))。为什么这不工作?试图通过索引访问boost numpy数组是否是一个问题?

+0

根据该文件,就可以构造一个来自python列表的数组。你有没有尝试一下:'bp :: list l; l.append(-INFINITY); l * = x; bnp :: ndarray foo = bnp :: array(l)'?不幸的是,我没有搭建一个带有numpy支持的boost python来测试它。 –

+0

你可以在算法头中使用std :: fill来初始化向量或数组 – Kochoba

+0

@Kochoba请你详细说明这个问题是如何适用的?根据我的发现,从'std :: vector'获得'boost :: python :: list'最直接的方法是在循环中追加。使用'boost :: python :: numpy :: from_data'看起来不像上面的4个语句更简洁。无论如何,我们将创建一个新的向量,所以我们可以直接在构造函数中填充它。还是你有其他想法?具体是什么? –

回答

1

这里有一个解决方案(谢谢@DanMašek了最初的想法),以及如何通过打印到控制台来验证:

bpy::list temp_list; 
temp_list.append(-INFINITY); 
temp_list *= x; 
bnp::ndarray foo = bnp::array(temp_list); 

在那里我有X = 9。验证W/

std::cout << std::endl << "Python ndarray : " << bpy::extract<char const *>(bpy::str(foo)) << std::endl; 

您也可以使用相同的temp_list给init另一个Python ndarray:

// after initializing bar the same as foo w/ temp_list 
bar[0] = 0; 
std::cout << std::endl << "Python ndarray : " << bpy::extract<char const *>(bpy::str(bar)) << std::endl; 

而导致打印出:

Python ndarray : [-inf -inf -inf -inf -inf -inf -inf -inf -inf] 

Python ndarray : [ 0. -inf -inf -inf -inf -inf -inf -inf -inf] 
+0

不错。一个评论 - 因为你将列表中的所有元素设置为相同的值,所以你可以像使用Python一样使用'*'运算符。 –

+1

酷感谢@DanMašek,回复更新。 – BoltzmannBrain