python中的real是什么意思_python – Cython中complex.real和creal(复杂)之间的区别

为了在cython中将实部与复杂部分分开,我通常使用complex.real和complex.imag来完成工作.然而,这确实生成了在html输出中略带“python red”的代码,我猜我应该使用creal(complex)和cimag(complex)代替.

考虑以下示例:

cdef double complex myfun():

cdef double complex c1,c2,c3

c1=1.0 + 1.2j

c2=2.2 + 13.4j

c3=c2.real + c1*c2.imag

c3=creal(c2) + c1*c2.imag

c3=creal(c2) + c1*cimag(c2)

return c2

c3的分配给出:

__pyx_v_c3 = __Pyx_c_sum(__ pyx_t_double_complex_from_parts(__ Pyx_CREAL(__ pyx_v_c2),0),_ _ pyx_c_prod(__ pyx_v_c1,__ pyx_t_double_complex_from_parts(__ Pyx_CIMAG(__ pyx_v_c2),0)));

__pyx_v_c3 = __Pyx_c_sum(__ pyx_t_double_complex_from_parts(creal(__ pyx_v_c2),0),_ _ pyx_c_prod(__ pyx_v_c1,__ pyx_t_double_complex_from_parts(__ Pyx_CIMAG(__ pyx_v_c2),0)));

__pyx_v_c3 = __Pyx_c_sum(__ pyx_t_double_complex_from_parts(creal(__ pyx_v_c2),0),_ _ pyx_c_prod(__ pyx_v_c1,__ pyx_t_double_complex_from_parts(cimag(__ pyx_v_c2),0)));

第一行使用(python着色)构造__Pyx_CREAL和__Pyx_CIMAG.

这是为什么,它是否会“显着”影响性能?

解决方法:

肯定是默认的C库

(complex.h)会奏效

为了你.

但是,这个图书馆似乎不会给你任何重大改进

与c.real c.imag方法相比.通过将代码放在一个

使用nogil:block,您可以检查您的代码是否已经无法调用

Python API:

cdef double complex c1, c2, c3

with nogil:

c1 = 1.0 + 1.2j

c2 = 2.2 + 13.4j

c3 = c2.real + c1*c2.imag

我使用的是Windows 7和Python 2.7,它没有可用的complex.h

用于Visual Studio编译器9.0的内置C库(与Python 2.7兼容).

因此,我创建了一个等效的纯C函数来检查任何可能的

与c.real和c.imag相比的收益:

cdef double mycreal(double complex dc):

cdef double complex* dcptr = &dc

return (dcptr)[0]

cdef double mycimag(double complex dc):

cdef double complex* dcptr = &dc

return (dcptr)[1]

运行以下两个测试功能后:

def myfun1(double complex c1, double complex c2):

return c2.real + c1*c2.imag

def myfun2(double complex c1, double complex c2):

return mycreal(c2) + c1*mycimag(c2)

得到时间:

In [3]: timeit myfun1(c1, c2)

The slowest run took 17.50 times longer than the fastest. This could mean that a

n intermediate result is being cached.

10000000 loops, best of 3: 86.3 ns per loop

In [4]: timeit myfun2(c1, c2)

The slowest run took 17.24 times longer than the fastest. This could mean that a

n intermediate result is being cached.

10000000 loops, best of 3: 87.6 ns per loop

确认c.real和c.imag已经足够快了.

标签:python,cython,complex-numbers,complextype

来源: https://codeday.me/bug/20190622/1264096.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值