3
$\begingroup$

I'm having some trouble with

Mod[k, 2] == 0 

versus

EvenQ[k]

They are sometimes yielding different results when given the same input.

A function I'm attempting to define:

sinmultipletheta[n_] := 
  ComplexExpand[Im[(Cos[θ] + I Sin[θ])^n]] /.
    {Cos[θ]^k_ -> 
      If[Mod[k, 2] == 0, 
        (1 - Sin[θ]^2)^(k/2), 
        (1 - Sin[θ]^2)^((k - 1)/2) Cos[θ]]} // Expand

This yields the correct answer. For example,

sinmultipletheta[9]
9 Sin[θ] - 120 Sin[θ]^3 + 432 Sin[θ]^5 - 576 Sin[θ]^7 + 256 Sin[θ]^9

When I replace Mod[k, 2] == 0 above with EvenQ[k], that is if I define

sinmultipletheta[n_] := 
  ComplexExpand[
    Im[(Cos[θ] + I Sin[θ])^n]] /. 
      {Cos[θ]^k_ -> 
        If[EvenQ[k], 
          (1 - Sin[θ]^2)^(k/2), 
          (1 - Sin[θ]^2)^((k - 1)/2) Cos[θ]]} // Expand

then

sinmultipletheta[9]
Sin[θ]^9 + 9 Cos[θ] Sin[θ] Sqrt[1 - Sin[θ]^2] - 
    111 Cos[θ] Sin[θ]^3 Sqrt[1 - Sin[θ]^2] + 
    321 Cos[θ] Sin[θ]^5 Sqrt[1 - Sin[θ]^2] - 
    255 Cos[θ] Sin[θ]^7 Sqrt[1 - Sin[θ]^2]

In this case, it seems my conditional statement is always evaluated as though it were false.

Any insight?

$\endgroup$
3
  • 5
    $\begingroup$ Check the documentation for EvenQ: "EvenQ[expr] returns False unless expr is manifestly an even integer (i.e. has head Integer, and is even)". This is different from Mod and Divisible. $\endgroup$ – unlikely Mar 23 '16 at 17:56
  • 3
    $\begingroup$ "An important feature of all the Wolfram Language property-testing functions whose names end in Q is that they always return False if they cannot determine whether the expression you give has a particular property. " $\endgroup$ – unlikely Mar 23 '16 at 18:08
  • 1
    $\begingroup$ Related: (109115). $\endgroup$ – user31159 Mar 23 '16 at 19:59
2
$\begingroup$
Clear[sinmultipletheta]

sinmultipletheta[n_] := 
 ComplexExpand[
    Im[(Cos[θ] + I Sin[θ])^n]] /. {Cos[θ]^k_ -> 
     If[Mod[k, 2] == 
       0, (1 - Sin[θ]^2)^(k/
         2), (1 - Sin[θ]^2)^((k - 1)/2) Cos[θ]]} // Expand

expr1 = sinmultipletheta[9]

(*  9 Sin[θ] - 120 Sin[θ]^3 + 432 Sin[θ]^5 - 
 576 Sin[θ]^7 + 256 Sin[θ]^9  *)

expr2 = sinmultipletheta[n]

(*  Sin[n Arg[Cos[θ] + I Sin[θ]]]  *)

Clear[sinmultipletheta]

Use RuleDelayed to keep the RHS of the rule from being evaluated until the function is called.

sinmultipletheta[n_] := 
 ComplexExpand[
    Im[(Cos[θ] + I Sin[θ])^n]] /. {Cos[θ]^k_ :> 
     If[EvenQ[k], (1 - Sin[θ]^2)^(k/
         2), (1 - Sin[θ]^2)^((k - 1)/2) Cos[θ]]} // Expand

expr3 = sinmultipletheta[9]

(*  9 Sin[θ] - 120 Sin[θ]^3 + 432 Sin[θ]^5 - 
 576 Sin[θ]^7 + 256 Sin[θ]^9  *)

expr4 = sinmultipletheta[n]

(*  Sin[n Arg[Cos[θ] + I Sin[θ]]]  *)

expr1 == expr3

(*  True  *)

expr2 == expr4

(*  True  *)
$\endgroup$

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