4
$\begingroup$

I would like to write a program to find the leading coefficient of a given polynomial. (Sounds easy, right?) I'd like to be able to handle the format x^2-x+7 (with any formal variable x) as well as the format #^2-#+7&. I would also like to be able to reject/error on inputs which are not univariate polynomials.

I thought the function Variables would make this easy, but it turns out that

Variables[#^2-#+7&]

gives

{#1^2 - #1 + 7 &}

which isn't helpful. My current plan:

  1. Check if the input is a function; if so, substitute f[\[FormalX]] for f.
  2. Check if Variables[f] has length other than 1; if so, fail.
  3. Define x as Variables[f][[1]] and return Coefficient[f,x,Exponent[f,x]].

But I'm stuck on the first step. Is there a good way to do this? Is there a better approach to what I'm trying to do?

$\endgroup$
6
  • $\begingroup$ Does checking the head work, i.e. yourFunction[x_Function]:= do something to x.? $\endgroup$ – N.J.Evans Apr 25 '16 at 16:39
  • 3
    $\begingroup$ Variables[#^2 - # + 7] will work, tho. $\endgroup$ – J. M.'s ennui Apr 25 '16 at 16:40
  • $\begingroup$ @J.M. That's interesting -- is there a way to convert an anonymous function to this form automatically? $\endgroup$ – Charles Apr 25 '16 at 16:41
  • $\begingroup$ Variables@First@Function[#^2 - # + 7] $\endgroup$ – march Apr 25 '16 at 16:52
  • 1
    $\begingroup$ BTW, you might also be interested in PolynomialQ[]. $\endgroup$ – J. M.'s ennui Apr 25 '16 at 16:59
2
$\begingroup$
lead[f_Function ] := lead[f@\[FormalX]]
lead[f_?PolynomialQ] /; (Length[(v = Variables[f])] == 1) := 
 Last@CoefficientList[f, v[[1]]]
lead[2 x^2 - x + 7 ]
lead[ 3 #^2 - # + 7 &]

2

3

Note this breaks if you supply a pure function with more than one slot. See here if you need to deal with that: How can I get the number of slots in Function?

$\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.