Skip to content

Commit

Permalink
Add Coefficient.
Browse files Browse the repository at this point in the history
  • Loading branch information
corywalker committed Jul 5, 2017
1 parent af2938d commit 82ccb1b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions expreduce/builtin_power.go
Expand Up @@ -340,5 +340,24 @@ func GetPowerDefinitions() (defs []Definition) {
&SameTest{"{0,1}", "Exponent[1 + x + x^2 - (x*(1 + 2*x))/2, x, List]"},
},
})
defs = append(defs, Definition{
Name: "Coefficient",
Usage: "`Coefficient[p, form]` returns the coefficient of form `form` in polynomial `p`.",
SimpleExamples: []TestInstruction{
&SameTest{"3", "Coefficient[(a + b)^3, a*b^2]"},
},
Tests: []TestInstruction{
&SameTest{"j", "Coefficient[c + j*a + k*b, a]"},
&SameTest{"a", "Coefficient[c + k*x + a*x^3, x, 3]"},
&SameTest{"24", "Coefficient[2*b*(2*a + 3*b)*(1 + 2*a + 3*b), a*b^2]"},
&SameTest{"29", "Coefficient[(2 + x)^2 + (5 + x)^2, x, 0]"},
&SameTest{"1", "Coefficient[a + x, x]"},
&SameTest{"4", "Coefficient[2*b*(2*a + 3*b)*(1 + 2*a + 3*b), a*b]"},
&SameTest{"1", "Coefficient[x^2, x^2]"},
&SameTest{"-a", "Coefficient[x^2 - x*(a + x), x]"},
&SameTest{"-(1/a)+b", "Coefficient[1 + b*x + x^2 - (x*(1 + a*x))/a, x]"},
&SameTest{"1/2", "Coefficient[1 + x + x^2 - (x*(1 + 2*x))/2, x]"},
},
})
return
}
19 changes: 19 additions & 0 deletions expreduce/resources/power.er
Expand Up @@ -31,3 +31,22 @@ Exponent[expr_,var_,head_]:=Module[{e=expr,v=var,h=head,theCases,toCheck},
Exponent[expr_,var_]:=Exponent[expr,var,Max];

Attributes[Exponent] = {Listable, Protected};

ExpreduceSingleCoefficient[inP_, inTerm_] :=
Module[{p = inP, term = inTerm, pat},
(*If[MatchQ[p,term],Return[1]];*)
pat = If[term === 1, a_?NumberQ, Optional[a_]*term];
(*pat=Optional[a_]*term;*)
If[MatchQ[p, pat],
(p) /. pat -> a, 0]
];
Coefficient[p_, var_, exp_] := Coefficient[p, var^exp];
Coefficient[inP_, inTerm_] :=
Module[{p = inP, term = inTerm, toMatch},
toMatch = p // Expand;
If[Head[toMatch] === Plus,
Map[ExpreduceSingleCoefficient[#, term] &, toMatch],
ExpreduceSingleCoefficient[toMatch, term]]
];

Attributes[Coefficient] = {Listable, Protected};

0 comments on commit 82ccb1b

Please sign in to comment.