如何用numpy在Cython中表示inf或-inf? [英] How to represent inf or -inf in Cython with numpy?

查看:97
本文介绍了如何用numpy在Cython中表示inf或-inf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用cython逐个元素构建一个数组.我想在某些条目中存储常量np.inf(或-1 * np.inf).但是,这将需要返回Python来查找inf的开销.是否有一个等于该常量的libc.math?还是一些易于使用的等效于(-1*np.inf)的值,可以在Cython中使用而没有开销?

I am building an array with cython element by element. I'd like to store the constant np.inf (or -1 * np.inf) in some entries. However, this will require the overhead of going back into Python to look up inf. Is there a libc.math equivalent of this constant? Or some other value that could easily be used that's equivalent to (-1*np.inf) and can be used from Cython without overhead?

EDIT 示例,您有:

cdef double value = 0
for k in xrange(...):
  # use -inf here -- how to avoid referring to np.inf and calling back to python?
  value = -1 * np.inf

推荐答案

没有文字,但是float可以从字符串中解析它:

There's no literal for it, but float can parse it from a string:

>>> float('inf')
inf
>>> np.inf == float('inf')
True

或者,math.h 可以(几乎可以肯定)声明一个计算为inf的宏,在这种情况下,您可以使用该宏:

Alternatively, math.h may (almost certainly will) declare a macro that evaluates to inf, in which case you can just use that:

cdef extern from "math.h":
    float INFINITY


(没有一种干净的方法来检查是否在纯Cython中定义了INFINITY,因此,如果您想覆盖所有基础,就需要hacky.一种方法是创建一个小的C标头,说fallbackinf.h:

#ifndef INFINITY
#define INFINITY 0
#endif

然后在您的.pyx文件中:

And then in your .pyx file:

cdef extern from "math.h":
    float INFINITY

cdef extern from "fallbackinf.h":
    pass

inf = INFINITY if INFINITY != 0 else float('inf')

(您不能将其分配给INFINITY,因为它是一个右值.如果您在标头中将INFINITY定义为1.0/0.0,则可以取消三元运算符,但这可能会提高SIGFPE,这取决于您的编译器.)

(You can't assign to INFINITY, because it's an rvalue. You could do away with the ternary operator if you #defined INFINITY as 1.0/0.0 in your header, but that might raise SIGFPE, depending on your compiler.)

但是,这绝对是对货物崇拜的最优化.)

This is definitely in the realm of cargo cult optimisation, though.)

这篇关于如何用numpy在Cython中表示inf或-inf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆