1
$\begingroup$

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?

$\endgroup$
4
  • $\begingroup$ Try: myList = {1, 2}; NIntegrate[myList[[IntegerPart[t]]], {t, 1., 2.5}] // Quiet $\endgroup$ Jan 4, 2022 at 11:50
  • 2
    $\begingroup$ 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. $\endgroup$
    – flinty
    Jan 4, 2022 at 12:17
  • 3
    $\begingroup$ @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. $\endgroup$ Jan 4, 2022 at 14:14
  • $\begingroup$ Use Floor rather than IntegerPart, i.e., Integrate[Floor[t], {t, 1, 5/2}] $\endgroup$
    – Bob Hanlon
    Jan 4, 2022 at 15:03

2 Answers 2

3
$\begingroup$

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 *)
$\endgroup$
2
$\begingroup$

This is what Indexed is useful for:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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