TransWikia.com

Integral of a function defined with a loop

Mathematica Asked by Glib Verovkin on February 1, 2021

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?

One Answer

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[10]]

enter image description here

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

enter image description here

Answered by Bob Hanlon on February 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP