快速列出PackedArray的产品标志? [英] Fast list-product sign for PackedArray?

查看:89
本文介绍了快速列出PackedArray的产品标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我先前的问题的延续,西蒙的查找PackedArray列表产品的方法很快,但是不适用于负值.

As a continuation of my previous question, Simon's method to find the list product of a PackedArray is fast, but it does not work with negative values.

可以通过Abs对其进行固定",而花费的时间最少,但是该标志丢失了,因此我需要分别查找产品标志.

This can be "fixed" by Abs with minimal time penalty, but the sign is lost, so I will need to find the product sign separately.

我尝试过的最快方法是EvenQ @ Total @ UnitStep[-lst]

The fastest method that I tried is EvenQ @ Total @ UnitStep[-lst]

lst = RandomReal[{-2, 2}, 5000000];

Do[
  EvenQ@Total@UnitStep[-lst],
  {30}
] // Timing

Out[]= {3.062, Null}

有更快的方法吗?

推荐答案

这比您的解决方案快两倍多,并且除了使用Rule@@@提取相关术语的废话外,我发现它更清楚-它只计算每个符号的数字元素.

This is a little over two times faster than your solution and apart from the nonsense of using Rule@@@ to extract the relevant term, I find it more clear - it simply counts the number elements with each sign.

EvenQ[-1 /. Rule@@@Tally@Sign[lst]]

比较时间(和输出)

In[1]:= lst=RandomReal[{-2,2},5000000];
        s=t={};
        Do[AppendTo[s,EvenQ@Total@UnitStep[-lst]],{10}];//Timing
        Do[AppendTo[t,EvenQ[-1/.Rule@@@Tally@Sign[lst]]],{10}];//Timing
        s==t
Out[3]= {2.11,Null}
Out[4]= {0.96,Null}
Out[5]= True

这篇关于快速列出PackedArray的产品标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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