Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting expressions in Mathematica

If I want to count the number of times that ^ occurs in an expression x, that's easy:

Count[x, _Power, {0, Infinity}]

Suppose I want to count only instances of -1 raised to some power. How can I do that?

I had tried

Count[(-1)^n + 2^n, _Power[-1, _], {0, Infinity}]

and even

Count[Plus[Power[-1, n], Power[2, n]], _Power[-1, _], {0, Infinity}]

but both gave 0.

The origin of the question: I'm building a ComplexityFunction that allows certain expressions like Power[-1, anyComplicatedExpressionHere] and Sqrt[5] (relevant to my problem) but heavily penalizes other uses of Power and Sqrt.

like image 619
Charles Avatar asked Dec 13 '22 11:12

Charles


2 Answers

You would do Count[x,Power[-1,_], {0, Infinity}]

In[4]:= RandomInteger[{-1, 1}, 10]^RandomChoice[{x, y, z}, 10]

Out[4]= {(-1)^x, (-1)^x, 0^y, 0^z, (-1)^z, 1, 1, 1, (-1)^y, 0^x}

In[5]:= Count[%, (-1)^_, {0, Infinity}]

Out[5]= 4
like image 84
Sasha Avatar answered Jan 03 '23 18:01

Sasha


What is about

Count[expr, Power[-1, _], {0, Infinity}]

P.S. Example in the question is not correct. I think you probably mean

Count[x, _Power, {0, Infinity}]
like image 25
Alexey Popkov Avatar answered Jan 03 '23 18:01

Alexey Popkov