Re: Assignment problem
- To: mathgroup at smc.vnet.net
- Subject: [mg86367] Re: Assignment problem
- From: "jwmerrill at gmail.com" <jwmerrill at gmail.com>
- Date: Sun, 9 Mar 2008 05:05:36 -0500 (EST)
- References: <fqo8o1$suo$1@smc.vnet.net> <fqqs3b$kf5$1@smc.vnet.net>
On Mar 8, 5:42 am, Helen Read <r... at math.uvm.edu> wrote: > Albert Retey wrote: > > > Note that usually using a Do-Loop is the better choice in Mathematica: > > (as compared with a For loop). > > This is the second post I've seen today that says that Do loops are > better than For loops in Mathematica. What is better about them (aside > from slightly simpler syntax)? > > -- > Helen Read > University of Vermont Mostly the slightly simpler syntax. For is more general, the downside being that you have to be more careful to understand exactly what it's doing. For instance, you can mess with the iterator inside a For loop, but not inside a Do loop: For[n = 1, n <= 5, n++, Print[n]; If[n == 1, n = 3]] 1 4 5 Do[Print[n]; If[n == 1, n = 3], {n, 1, 5}] 1 2 3 4 5 I think it's more easy to make off-by-one errors using a for loop. Do is a little faster. In[57]:= Timing[Do[Factor[n], {n, 1, 1000000}]] Out[57]= {1.22538, Null} In[58]:= Timing[For[n = 1, n <= 1000000, n++, Factor[n]]] Out[58]= {3.10699, Null} It's partly a stylistic kind of thing. Mathematica lets you do procedural style programming, but the functional style is closer to it's sweet spot. In this example, the difference is small, but if you want to do something like square a bunch of numbers, then it's a lot nicer to do In[59]:= numbers = {1, 12, 50}; result = Map[#^2 &, numbers] Out[60]= {1, 144, 2500} than In[106]:= numbers = {1, 12, 50}; result = {Null, Null, Null}; For[n = 1, n <= Length[numbers], n++, result[[n]] = numbers[[n]]^2] result Out[109]= {1, 144, 2500} There is so often a better way to do things than using a For loop (the difference can be very small or somewhat less small), that my first instinct is to avoid For entirely except under very special circumstances. Regards, JM