Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #10921

Re: Replace, ReplaceAll and If time performace comparition

From Dana DeLouis <dana01@me.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Replace, ReplaceAll and If time performace comparition
Date 2012-07-14 05:31 +0000
Message-ID <jtr07r$bd3$1@smc.vnet.net> (permalink)
Organization Time-Warner Telecom

Show all headers | View raw


> (If[# < 0, 0, #] & /@ randomList); // AbsoluteTiming
> {0.572200, Null}
> ...  There is some trick to make it faster?


Hi.   You've got a great solution with Clip, but just to add 2 cents..

In other programming languages, sometimes using Max or Min instead of an IF statement is nice.

randomList=RandomInteger[{-100,100},10 10^6];

t1=(If[#<0,0,#]&/@randomList);//AbsoluteTiming
{0.729998,Null}

t2=(Max[#,0]&/@randomList);//AbsoluteTiming
{0.454711,Null} 

t1==t2
True


In the old days before Clip, one way was to use two IF statements.
One neat technique was to replace the two IF statements with Median.

v=RandomInteger[{-100,100},20];

// New
Clip[v,{0,1}]
{0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0}

// Old days 
Median[{0,#,1}]& /@v
{0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0}

%%==%
True

If one were stuck without access to a Median function, then one way without IF statements...

Min[Max[0,#],1]& /@ v
{0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0}

= = = = = = = = = =
Dana DeLouis
Mac & Math 8
= = = = = = = = = =



On Jun 24, 4:24 am, Murta <rodrigomur...@gmail.com> wrote:
> HI all
> I was working in some simulations with random numbers and get this example of performance comparition.
> 
> randomList = RandomInteger[{-100, 100}, 10 10^6];
> 
> (randomList /. (x_ /; x < 0 -> 0)); // AbsoluteTiming
> {5.747133, Null}
> 
> Replace[randomList, (x_ /; x < 0 -> 0), 1]; // AbsoluteTiming
> {4.758984, Null}
> 
> (If[# < 0, 0, #] & /@ randomList); // AbsoluteTiming
> {0.572200, Null}
> 
> I personally prefer work with patterns because they are more compact and functional.
> Someone knows why patter is one magnitude order slow?? There is some trick to make it faster?
> 
> tks
> Murta


Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Replace, ReplaceAll and If time performace comparition Dana DeLouis <dana01@me.com> - 2012-07-14 05:31 +0000

csiph-web