1
$\begingroup$

Let tally=RandomInteger[{0, 1}, 10];

In the code below, I'm trying to output a list where each component $C_n=\sum^n_{i=1} \text{tally}_i / n$

The problem with my code below is that when tally [[i]] == 0, it doesn't change the component value as the formula above...

j = 0;
acceptanceplot = 
  ReplacePart[tally , {i_} /; tally [[i]] == 1 :> (j++/i)];
ListPlot[acceptanceplot[[1 ;; Length[tally]]]]

Is there a possibility of adding a second condition, or an else clause to $/;$? If possible, then I would just add the action j/i

$\endgroup$
  • 1
    $\begingroup$ Can you just string your clauses together with && or |? $\endgroup$ – Carl Lange Jan 27 at 17:41
  • $\begingroup$ @CarlLange I'm not sure of what you're suggesting... Could you elaborate on it? $\endgroup$ – An old man in the sea. Jan 27 at 18:12
  • $\begingroup$ I don't think your way of constructing the new list in place of the old is a good idea: you assume that ReplacePart scans the elements in order, which is not specified in the manual and thus could change in different circumstances (e.g. parallelization). $\endgroup$ – Roman Jan 27 at 18:54
7
$\begingroup$
SeedRandom[0]

tally = RandomInteger[{0, 1}, 10];

acceptanceplot = Accumulate[tally]/Range[Length[tally]];

ListPlot[acceptanceplot]

enter image description here

SeedRandom[0]

tally = RandomInteger[{0, 1}, 10^4];

acceptanceplot = Accumulate[tally]/Range[Length[tally]];

ListPlot[acceptanceplot]

enter image description here

$\endgroup$
2
$\begingroup$

I don't think that this necessarily the best way to solve the problem at hand, but I think I understand what the OP means in terms of adding an "else clause" to Condition (/;). Now it isn't possible to modify the condition itself, but instead you can just add an extra replacement rule that fires whenever the first one doesn't:

acceptanceplot = ReplacePart[
  tally,
  {
   {i_} /; tally[[i]] == 1 :> j++/i,
   {i_} :> j/i
   }
]

If the first rule matches, that one will fire. Otherwise the less restrictive second rule will be applied.

$\endgroup$
  • $\begingroup$ Many thanks Sjoerd for your answer. +1 ;) $\endgroup$ – An old man in the sea. Jan 27 at 20:02
0
$\begingroup$
acceptance = Rest@FoldList[Plus, 0, tally]/Range[Length[tally]]
$\endgroup$
  • $\begingroup$ Accumulate[tally] is simpler than Rest@FoldList[Plus, 0, tally], see @BobHanlon above. $\endgroup$ – Roman Jan 27 at 19:26
  • $\begingroup$ Thanks for the effort Roman. ;) $\endgroup$ – An old man in the sea. Jan 27 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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