Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: For loop problem in mathematica

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90192] Re: For loop problem in mathematica
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Wed, 2 Jul 2008 05:28:01 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <g4d2qf$emo$1@smc.vnet.net>

PhysNova wrote:

> i wrote a simple program of evaluating Pi number in M6 to test cpu
> computation timing, to do this a simple for loop
> 
> was used:

As posted, the code below *cannot* work since it is syntacticly 
incorrect and possibly logically flawed.

> x=0;For[i = 1, i < 10,000,000, i++, x = x + 1/(i^2)];N[Sqrt(6*x),25]//
---------------------!!!![1]!!!------------------------------![2]!------
> Timing
--!![3]!

[1] You cannot use commas here. You must write 10000000.
[2] If you want the square root, you must use square brackets: Sqrt[6*x]
[3] Assuming the syntax errors are corrected, what you are timing is not 
the cpu time for the For loop, but just the time for N[Sqrt[6*x],25]

To understand what is going on, you should familiarize yourself with the 
three arithmetic models (exact -- or infinite --, arbitrary, and machine 
precision). You could start at

http://reference.wolfram.com/mathematica/tutorial/\
ExactAndApproximateResults.html

Then, evaluate and compare the results of the following expressions


In[1]:= x = 0.;
For[i = 1., i < 1000., i++, x = x + 1/(i^2);
   N[Sqrt[6*x], 25]] // Timing

Out[2]= {0.006855, Null}

In[3]:= x = 0;
For[i = 1, i < 1000, i++, x = x + 1/(i^2);
   N[Sqrt[6*x], 25]] // Timing

Out[4]= {8.21297, Null}

In[5]:= x = 0.;
Table[x = x + 1/(i^2), {i, 1000}]

Out[6]= {1., 1.25, 1.36111, 1.42361, 1.46361, 1.49139, 1.5118, \
1.52742, 1.53977, 1.54977, 1.55803, 1.56498, 1.57089, 1.576, 1.58044, \
1.58435, 1.58781, 1.59089, 1.59366, 1.59616, 1.59843, 1.6005, \

[... rest of the output deleted ... ]

In[7]:= x = 0;
Table[x = x + 1/(i^2), {i, 1000}]

Out[8]= {1, 5/4, 49/36, 205/144, 5269/3600, 5369/3600, 266681/176400, \
1077749/705600, 9778141/6350400, 1968329/1270080, \
239437889/153679680, 240505109/153679680, 40799043101/25971865920, \
40931552621/25971865920, 205234915681/129859329600, \
822968714749/519437318400, 238357395880861/150117385017600, \
238820721143261/150117385017600, 86364397717734821/54192375991353600, \
17299975731542641/10838475198270720, 353562301485889/221193371393280, \
354019312583809/221193371393280, \

[... rest of the output deleted ... ]

<snip>

Regards,
-- Jean-Marc


  • Prev by Date: Re: On the built-in function "Compile"
  • Next by Date: Re: Draw two functions in a graph, one of them does also
  • Previous by thread: Re: For loop problem in mathematica
  • Next by thread: Re: For loop problem in mathematica