2
$\begingroup$

Edit: My original question implicated D in the problem, but it seems unrelated, so I've removed that part of the question.

I am writing a function that uses functions involving subscripts and an open-ended Sum. It's unreasonably slow. Here's a minimal example (the real situation is much worse):

Sum[
  -2 Exp[-(xx - Subscript[x, k])^2/(V + Subscript[Vx, k]^2)] Subscript[n, k] (xx - Subscript[x, k])/(V + Subscript[Vx, k]^2)
, {k, nsp}] // AbsoluteTiming

enter image description here

Sum[
  -2 Exp[-(xx - subscript[x, k])^2/(V + subscript[Vx, k]^2)] subscript[n, k] (xx - subscript[x, k])/(V + subscript[Vx, k]^2)
, {k, nsp}] // AbsoluteTiming

enter image description here

Well, good thing I'm not using Superscript, because that's 10X worse:

Sum[
  -2 Exp[-(xx - Superscript[x, k])^2/(V + Superscript[Vx, k]^2)] Superscript[n, k] (xx - Superscript[x, k])/(V + Superscript[Vx, k]^2)
, {k, nsp}] // AbsoluteTiming

enter image description here

So, is there some way to tell Sum not to bother trying anything fancy? And what's with the 100-fold range of timing of otherwise identical code?

N.B.: these timings change on rerunning the same code due to some kind of caching

$\endgroup$
8
  • $\begingroup$ This is not a speed-up from "without subscripts" but after using "without subscripts" just apply x_[j] -> Subscript[x, j]]. $\endgroup$
    – JimB
    Jun 26 at 21:27
  • 2
    $\begingroup$ Use Format[x[j_]] := Subscript[x, j] and similar, then the indexed variables will display as subscripts in the output. $\endgroup$
    – Bob Hanlon
    Jun 26 at 23:35
  • $\begingroup$ You could use Block to temporarily redefine Sum and Subscript with your own versions. These need only implement minimal functionality $\endgroup$
    – mikado
    Jun 27 at 7:05
  • $\begingroup$ @JimB Yeah I thought of that, but applying that back-transformation eats up basically all of the time-savings. $\endgroup$
    – Chris K
    Jun 27 at 15:30
  • 3
    $\begingroup$ Why not wrap Inactive around your sum, i.e., D[Inactive[Sum][...], ..]? $\endgroup$
    – Carl Woll
    Jun 27 at 16:04
3
$\begingroup$

Seems like the Sum option I was looking for is Method -> "Procedural":

Sum[
  -2 Exp[-(xx - Subscript[x, k])^2/(V + Subscript[Vx, k]^2)] Subscript[n, k] (xx - Subscript[x, k])/(V + Subscript[Vx, k]^2)
, {k, nsp}, Method -> "Procedural"] // AbsoluteTiming

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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