# Integral involving Part

The integral below is a simple prototype of something I'm interested in. It causes an error whose origin I understand but haven't been able to fix.

myList={1,2}; NIntegrate[myList[[IntegerPart[t]]],{t,1.,2.5}]

Part::pkspec1: The expression IntegerPart[t] cannot be used as a part specification.

Is there a way to to get rid of the error message while maintaining the basic idea?

• Try: myList = {1, 2}; NIntegrate[myList[[IntegerPart[t]]], {t, 1., 2.5}] // Quiet Jan 4, 2022 at 11:50
• You could also hide it behind a function and force a numeric input: myList = {1, 2}; f[t_?NumericQ] := myList[[IntegerPart[t]]]; NIntegrate[f[t], {t, 1., 2.5}] Interestingly NIntegrate will then produce convergence warnings instead and gives 2.00012 - a different result from Mariusz's 2. Jan 4, 2022 at 12:17
• @flinty It's just a different method being used, one that ends up being less accurate. This is an unfortunate (and possibly unavoidable) drawback of using black-box functions. One issue is that error estimates are more difficult due to need to compute derivatives by numeric approximation. Jan 4, 2022 at 14:14
• Use Floor rather than IntegerPart, i.e., Integrate[Floor[t], {t, 1, 5/2}] Jan 4, 2022 at 15:03

NIntegrate first symbolically analyses the input and complains about the index: IntegerPart[t]. To prevent this, define a function with numeric arguments:

myList = {1, 2};
fun[t_?NumericQ] := myList[[IntegerPart[t]]];


Now, this functions has jumps and the default method has trouble with this, resulting in error messages and an inaccurate result. Therefore, specify a method that samples the function strongly around the jumps:

NIntegrate[fun[t], {t, 1., 2.5}, Method -> "LocalAdaptive"]

(* 2 *)


This is what Indexed is useful for:

NIntegrate[Indexed[myList, IntegerPart[t]], {t, 1., 2.5}]