I'm not sure of the range of cases for the fraction that you want to deal with. For instance:
- Is the numerator always a monomial?
- Does the numerator ever have more than one numeric factor?
- Is there ever more than one parameter or variable?
I'm guessing the answers are "yes," "no", and "no," respectively. But the second one is tricky. I don't think the code works, according to my understanding of what is desired, on the following fractions:
frac = -((Sqrt[8] m^2)/(3 + 10 m^2 + 3 m^4))
frac = -((Sqrt[2] m^2)/(3 + 10 m^2 + 3 m^4))
frac = -(((1 + Sqrt[2]) m^2)/(3 + 10 m^2 + 3 m^4)) (* a real disaster! :) *)
These have more than one numeric factor (inspect the FullForm) in the numerator, and your (Cases…)[[1]] code grabs only the first. Perhaps the coefficients are always single numbers,
maybe always integers even,
and not arbitrary numeric expressions.
Here is another way to separate the coefficient of a monomial numerator:
(* change fraction as desired. I picked a complicated one to show robustness *)
num = Numerator[-((Sqrt[8] m^2 p^3)/(3 + 10 m^2 + 3 m^4))];
vars = Variables[num]; (* change vars to {m} to include p in the coefficient *)
{coeff, fac} = Replace[
CoefficientRules[num, vars],
{{pow_ -> coeff_} :> {coeff, Times @@ (vars^pow)},
_ :> (* should really pick another action :) *)
"Oh, no, num is not a monomial!" }
]
(* {-2 Sqrt[2], m^2 p^3} *)
Another alternative, which separates the numeric factors from the rest of the numerator:
{coeff, fac} = Times @@@ Lookup[
GroupBy[Power @@@ FactorList[num], NumericQ],
{True, False},
{}]
(* {-2 Sqrt[2], m^2 p^3} *)
A tip for a slightly neater code: You call NumeratorDenominator[] and Numerator[] several times. One could save the result in variables with one call and use the variables in the code:
{num, den} = NumeratorDenominator[frac];
If you want to test whether an expression is a rational function with integer coefficients, one can use this:
AllTrue[
NumeratorDenominator@Together@expr,
PolynomialExpressionQ[#, {m}, IntegerQ] &]
We don't really need to use Together@in or Together@frac above, because those fractions are already "together."