fun = a+b+c+d/e

If we want to get the number of summands, we can use Length[fun], which properly gives 5 in this case. However, if fun contains only a single term

fun = d/e

Then applying Length[fun] gives 2 since now it actually counts the number of terms in the multiplication instead of summation.

Therefore, Length is rather a hack than an actually reliable function to get the number of summands. Is there an efficient function that returns the number of summands reliably?

  • $\begingroup$ How complicated are these expressions? Will there ever be nested summands, like Cos[a + b] + Sin[c + d]? And in this case, is the answer 2? $\endgroup$ – march Dec 3 '15 at 17:04
  • $\begingroup$ @march Yes, and yes. $\endgroup$ – Kagaratsch Dec 3 '15 at 17:05
  • $\begingroup$ Also, should expressions like (a + b)^2 be treated as having length 1 or length 3? (i.e should the expressions be expanded as much as possible before calculating a length?) $\endgroup$ – march Dec 3 '15 at 17:07
  • $\begingroup$ @march Yes, we better assume that we want to count fun//Expand. Otherwise the summand counting function will probably get really slow. $\endgroup$ – Kagaratsch Dec 3 '15 at 17:09

Best thing I can come up with is

cntSummands[expr_]:=If[Head[expr]===Plus,Length[expr],If[expr === 0, 0, 1]]

but this sounds like a terrible workaround. I am sure there are better ways?

  • 2
    $\begingroup$ Frankly, that doesn't seem to bad to me. I would just add an Expand@ before expr on the right hand side. $\endgroup$ – march Dec 3 '15 at 17:20

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.