# Integral of a function defined with a loop

I have defined a function g as

g[t_] := (
res = 0;
i = 1;
While[i <= t,
res = res + i;
i = i + 1;
];
res);


The aim is to work with the function F[u], which should be the integral of g in bounds $$[0,u]$$, something like

F[u_] := Integrate[g[y], {y, 0, u}]


However, the result I obtain for F is not correct with such definition of g. In fact, F takes value 0 for any argument u (my guess is that this happens because g[y] is immediately evaluated as 0).

How can F be redefined properly, without changing the definition of g?

• Use g[t_?NumericQ] := ... instead, then do Remove["Global*"] and re-evaluate it. See here for other cases where NumericQ is needed. – flinty Dec 26 '20 at 14:05
• Is there a reason you don't want to simply define g[t_] := Floor[t] (Floor[t] + 1) / 2? – Greg Martin Dec 27 '20 at 3:18
• The idea is that g is a function defined exactly with a loop. In my research Im dealing with some counting stochastic process, which cannot be defined otherwise than a sum of random variables upto certain moment. Since stating the whole problem would have been rigorous, I have asked this more general question in order to apply obtained results later in my work. – Glib Verovkin Dec 27 '20 at 15:50

Clear["Global*"]


Use Module to keep the temporary variable names (and values) out of the Global context.

g[t_] := Module[{res = 0, i = 1},
While[i <= t, res = res + i; i = i + 1]; res];


However, note that g evaluates to 0 for symbolic arguments.

g[t]

(* 0 *)


Consequently, restrict its arguments to being NumericQ or preferably, Positive.

Clear[g]

g[t_?Positive] := Module[{res = 0, i = 1},
While[i <= t, res = res + i; i = i + 1]; res];


For comparison purposes, define

g2[t_] := Module[{m = Floor[t]}, m (m + 1)/2]


The argument of g2 does not need to be restricted.

g2[t]

(* 1/2 Floor[t] (1 + Floor[t]) *)


Numerically, g and g2 are equivalent for positive arguments.

Plot[{g[t], g2[t]}, {t, 0, 10}, PlotStyle -> {Automatic, Dashed},
PlotLegends -> Placed["Expressions", {.25, .75}],
Exclusions -> Range] The integrals are

F[u_?NumericQ] := Integrate[g[y], {y, 0, u}]

F2[u_?NumericQ] := Integrate[g2[y], {y, 0, u}]

Plot[{F[u], F2[u]}, {u, 0, 5}, PlotStyle -> {Automatic, Dashed},
PlotLegends -> Placed["Expressions", {.25, .75}]] // Quiet
` • That is exactly what I needed.Thanks a lot for your comprehensive answer! – Glib Verovkin Dec 27 '20 at 15:31