       Re: For loop problem in mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg90213] Re: For loop problem in mathematica
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Wed, 2 Jul 2008 05:32:01 -0400 (EDT)

```On 7/1/08 at 6:59 AM, skhoshbinfar at gmail.com (PhysNova) wrote:

>Hi, 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:

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

>the result was catastrophe! it take few minuates. but i first expect
>to do this very simple job in few

>seconds.computation time is just satisfactory up to 100000 cycle.

>could anyone interperet this falut? our get an idea to improve the
>result?

The bottom line in Mathematica is using For is one of the surest
ways to create slow code. Don't use For in Mathematica without
very good reasons. And so far, I've yet to find one very good
reason to use For.

The specific computation can be done as:

In:= Sqrt[6 Sum[1/n^2, {n, k}] /. k -> 10000000.] // Timing

Out= {0.016533,3.14159}

in far less than a second. Or if you want more precision,

In:= Sqrt[6 Sum[1/n^2, {n, k}] /. k -> N[10000000, 25]] // Timing

Out= {0.017678,3.141592558096830706654627046981}

somewhat slower but still a small fraction of a second

```

• Prev by Date: Re: Draw two functions in a graph, one of them does also
• Next by Date: Re: Draw two functions in a graph, one of them does also have a parameter.
• Previous by thread: Re: For loop problem in mathematica
• Next by thread: Re: For loop problem in mathematica