Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #7859
| From | DrMajorBob <btreat1@austin.rr.com> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: How to simplify this code with variable number of |
| Date | 2012-01-16 11:52 +0000 |
| Organization | Steven M. Christensen and Associates, Inc and MathTensor, Inc. |
| Message-ID | <jf1328$5h0$1@smc.vnet.net> (permalink) |
| References | <201201150951.EAA19677@smc.vnet.net> |
It's unclear what "for a[g]=a[g-1]+1 to 2g-1 do" might mean (for
instance), but I'll make a guess or two.
Possibly you mean
a[g] = a[g-1] + Sum[i,{i,1,2 g - 1,2}
or
a[g] = a[g-1] + Sum[i,{i,1,2 g - 1}
If so, both sums are simple:
Sum[i, {i, 1, 2 g - 1, 2}]
g^2
Sum[i, {i, 1, 2 g - 1}]
g (-1 + 2 g)
Defining a recursive function is also simple. For instance,
Clear[a]
a[0] = 0;
a[k_] := a[k - 1] + k^2
a[120]
583220
If I try a larger value, problems may occur:
a[1000]
$RecursionLimit::reclim: Recursion depth of 256 exceeded. >>
But that can be fixed:
Clear[a]
a[0] = 0;
a[k_] := a[k] = a[k - 1] + k^2
Do[a[k], {k, 1000}]
a[1000]
333833500
a memorizes its values as they are calculated, and Do calculates them in
order, hence recursion never has to go back more than one index.
If you want some index to be different than others, as implied by "###some
computations here###", then it might be:
g = 1000;
Clear[a]
a[0] = 0;
a[g] := a[g - 1] + whatever;
a[k_] := a[k] = a[k - 1] + k^2
Do[a[k], {k, 1000}]
a[1000]
332833500 + whatever
Bobby
On Sun, 15 Jan 2012 03:51:29 -0600, Rex <aoirex@gmail.com> wrote:
> Considering an array a[i], i=0,1,...,g, where g could be any given
> number, and a[0]=1.
>
> for a[1]=a[0]+1 to 1 do
> for a[2]=a[1]+1 to 3 do
> for a[3]=a[2]+1 to 5 do
> ......
> for a[g]=a[g-1]+1 to 2g-1 do
> ###some computations here###
>
> The problem is that everytime we change the value of g, we need to
> modify the code, those loops above. So this is not a good code.
>
> Any advice would be greatly appreciated.
>
--
DrMajorBob@yahoo.com
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: How to simplify this code with variable number of DrMajorBob <btreat1@austin.rr.com> - 2012-01-16 11:52 +0000
csiph-web