4

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?

Charles
  • 1,359
  • 8
  • 13

1 Answers1

2
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?

george2079
  • 38,913
  • 1
  • 43
  • 110