4
$\begingroup$

I want a list of the kind list = {a,a+b,a+b+c} for list plotting. The quantities of the list come from a function. Let us say this is

f[x_] = x^2

What I am doing is I start out with a list with a single entry, the first entry

dataset = {f[1]}

Then I write the following for loop

For[l = 2, l <= 50, l = l + 2, 
 AppendTo[dataset, dataset[[-1]] + f[l]]]

Obviously, this is very slow and further my function f[l] is actually a numerical sum of a very complicated expression. Is there any way to do this faster by using functional methods?

$\endgroup$

2 Answers 2

9
$\begingroup$
f[x_] := x^2

Accumulate[f /@ {1}~Join~Range[2, 50, 2]]

or

FoldList[#1 + f[#2] &, f[1], Range[2, 50, 2]]

{1, 5, 21, 57, 121, 221, 365, 561, 817, 1141, 1541, 2025, 2601, 3277, \ 4061, 4961, 5985, 7141, 8437, 9881, 11481, 13245, 15181, 17297,
19601, 22101}

$\endgroup$
2
  • $\begingroup$ Thanks @Syed . Is there a way to parallelize it? $\endgroup$
    – QFTheorist
    Apr 14 at 5:39
  • $\begingroup$ It depends on the size of the input. If the input is a large list, then you may see some gain. Try Parallelize for instance. I would say this requires more information, a typical calculation, size of the list and your adopted solution. My suggestion would be to start a fresh question. $\endgroup$
    – Syed
    Apr 14 at 5:50
2
$\begingroup$
Cumulate[f_, r_] := Module[{n = 1}, Prepend[1] @ Map[n += f[#] &] @ r]

f[x_] := x^2

Cumulate[f, Range[2, 50, 2]]

{1, 5, 21, 57, 121, 221, 365, 561, 817, 1141, 1541, 2025, 2601, 3277,
4061, 4961, 5985, 7141, 8437, 9881, 11481, 13245, 15181, 17297,
19601, 22101}

Without pre-defined f

Cumulate[#^2 &, Range[2, 50, 2]]

same result

Compare with Accumulate

Rest @ Cumulate[# &, Range[5]] - 1 == Accumulate @ Range[5]

True

$\endgroup$
2
  • $\begingroup$ Thanks @eldo. Is there a way to parallelize it? $\endgroup$
    – QFTheorist
    Apr 14 at 5:39
  • $\begingroup$ If f is "a very complicated expression" you could try to Compile it. $\endgroup$
    – eldo
    Apr 14 at 6:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.