Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #10124
| From | Dana DeLouis <dana01@me.com> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: unexpected behaviour of Sum |
| Date | 2012-05-18 09:25 +0000 |
| Organization | Steven M. Christensen and Associates, Inc and MathTensor, Inc. |
| Message-ID | <jp54i0$gmt$1@smc.vnet.net> (permalink) |
> Sum[sod[k],{k,10^6}] which gives 27000001 (ok)
Hi. Just for a mental exercise, this is the best I could do for a non Brute-Force method.
There are probably better ways:
(*
Sum the individual digits between 1 and n
Dana DeLouis
*)
AllDigitSum[n_]:=Module[
{
k,j,fn,fx,lst,w,
dig = IntegerDigits[n]
},
fn[z_]:=Power[10,z-1]*(z*45);
fx[start_,step_,z_]:=1/2 z((z-1) step+2 start);
lst=FoldList[Plus,0,dig];
w=Length[dig];
Sum[
k=Power[10,w-j];
fx[lst[[j]]*k+fn[w-j],k,dig[[j]]],
{j,1,w}]+lst[[-1]]
]
Here, the function f[ ] is the Brute Force looping method as given by your Sum function.
f[1000000] // Timing
{3.78069, 27000001}
AllDigitSum[1000000] //Timing
{0.00026, 27000001}
f[9876543] //Timing
{37.8118, 309922302}
AllDigitSum[9876543] //Timing
{0.000285, 309922302}
= = = = = = = = = =
HTH :>)
Dana DeLouis
Mac & Math 8
= = = = = = = = = =
On May 14, 1:34 am, perplexed <yudu...@gmail.com> wrote:
> I do not want to say that this is a bug, however I did
> not find, in the Sum documentation, an explanation of this
> behaviour (v8.0.4)
>
> I defined an innocent function like
> sod[n_]:=Plus@@IntegerDigits[n]
> that compute the sum of the digits of a number.
> (I tried with other functions, so the culprit is not IntegerDigits)
>
> Then I compute two sums:
> Sum[sod[k],{k,10^6}] which gives 27000001 (ok)
> then
> Sum[sod[k],{k,1+10^6}] which gives 500001500001 (nonsense).
> then
> Sum[sod[k],{k,2,1+10^6}] which gives 27000002 (ok)
>
> so, it seems to me that Sum has a problem when the iterator
> works in a range greater than 10^6.
>
> Indeed, I made an experiment:
> I set L={}; and defined
> sod[n_]:=(AppendTo[L,n];Plus@@IntegerDigits[n])
> Then Sum[sod[k],{k,1+10^6}] still gives 500001500001
> and at the end L is equal to {k}, so it seems that
> Sum tried to do something symbolic (??).
>
> Is this a bug or a feature whose documentation I was not
> able to find? Say, is there an option to fix things ?
>
> Btw, using ParallelSum instead of Sum works fine (and faster).
> thanks
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: unexpected behaviour of Sum Dana DeLouis <dana01@me.com> - 2012-05-18 09:25 +0000
csiph-web