# RandomReal inside a loop

I want to perform the following series summation: $$\sum_{j=1}^5 \exp\left[{-\beta \, \left(\text{En} + \frac{\Delta \, X}{Num} \right)}\right] \cos{\left(\text{En} + \frac{\Delta \, X \, T}{Num} \right)},$$

where $$X$$ is a random real number, which takes a different value for each of the 5 terms in the series, in the interval $$[0,1]$$. I am trying to implement the same using the following code:

Sum[ E^{-\[Beta] {En + \[CapitalDelta]/ Num RandomReal[]} } {Cos[{En + \[CapitalDelta]/ Num RandomReal[]} t]}, {J, 1, 5}]


Here the problem I am encountering is that the random number takes different values for the argument of the exponential and the argument of the cosine, while my case involves the same random number for both. How do I enforce that the argument X for a term in the series is the same, and not two different random reals within the same term in the series?

• Use a With and set the RandomReal[] in there Sum[With[{X = RandomReal[]},E^{-\[Beta] {En + \[CapitalDelta]/ Num X}} {Cos[{En + \[CapitalDelta]/Num X} t]}], {J, 1, 5}] – flinty Aug 10 '20 at 14:20
• @flinty Thanks, that works. – Learner Aug 10 '20 at 14:24

f[beta_, en_, x_, delta_, num_, t_] :=

• Yes. Use the procedural Total rather than the analytic Sum. Sometimes Sum figures out that you are using it procedurally, but it can get lost attempting symbolic analysis. – John Doty Aug 10 '20 at 16:29
• @John, indeed Total[] is appropriate here (especially if you use Method -> "CompensatedSummation"), but Sum[] can also be coerced to do no symbolic analysis at all via Method -> "Procedural". – J. M.'s ennui Aug 10 '20 at 16:32