I was curious about the difference in speed between Total
and Sum
. I found out Total
was faster. However on another occasion I used a longer list and then the result was reversed.
Upon closer inspection, I saw that Sum
behaved strangely, see the repetitive code below:
Sum[x, {x, 1, 10^4}] // AbsoluteTiming
Sum[x, {x, 1, 10^5}] // AbsoluteTiming
Sum[x, {x, 1, 10^6}] // AbsoluteTiming
Sum[x, {x, 1, 10^7}] // AbsoluteTiming
Sum[x, {x, 1, 10^8}] // AbsoluteTiming
Sum[x, {x, 1, 10^9}] // AbsoluteTiming
{0.000377, 50005000}
{0.002676, 5000050000}
{0.162434, 500000500000}
{0.000157, 50000005000000}
{0.000112, 5000000050000000}
{0.000110, 500000000500000000}
I can not make any sense of the results above.
Compare those with the more expected results from Total
Total[Range[10^4]] // AbsoluteTiming
Total[Range[10^5]] // AbsoluteTiming
Total[Range[10^6]] // AbsoluteTiming
Total[Range[10^7]] // AbsoluteTiming
Total[Range[10^8]] // AbsoluteTiming
Total[Range[10^9]] // AbsoluteTiming
{0.000115, 50005000}
{0.000931, 5000050000}
{0.010395, 500000500000}
{0.101801, 50000005000000}
{1.166246, 5000000050000000}
{12.470277, 500000000500000000}
Can anyone explain what causes this strange behavior ?
Total
will most surely sum blindly, whileSum[]
could use known properties (at least it will try whenn
is large enough) $\endgroup$sum[n_Integer?Positive] = Sum[x, {x, 1, n}]
$\endgroup$