在 Python 中,我可以使用以下命令初始化 x 长度的负 inf numpy 数组
import numpy as np
...
foo = np.array([np.NINF] * x)
哪里x
是一个 int 例如42. 我想用 Boost.Python 在 C++ 中做同样的事情。以下显然行不通:
namespace bnp = boost::python::numpy;
...
bnp::ndarray foo = bnp::array({-INFINITY} * x);
有哪些好的方法可以做到这一点?
是的,我知道 Boost.Numpy docs and tutorial -- 他们并不出色。
更一般地说,如何用值 -INFINITY 初始化长度为 x 的 std vector 或数组?
更新:
我正在尝试通过打印到控制台来验证方法(使用评论中建议的初始循环)
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 数组是否存在问题?
最佳答案
这是一个解决方案(感谢@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
来初始化另一个 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]
关于python - C++ Boost Python numpy 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616020/