# Get rational and irrational parts

Consider an expression of the form $a + b \sqrt{2}$, where $a,b \in \mathbb{Q}$. How can I extract $b$ (or equivalently $a$) from this expression?

One can define the conjugate and use it to construct the rational and radical coefficients (rat and rad resp.). Just as PowerExpand assumes bases are positive reals, conj[x] will be correct only if the symbolic variables and functions in an expression x represent rational numbers.

conj[x_] := x /. Sqrt[2] -> -Sqrt[2];
rat[x_] := (x + conj[x])/2;
rad[x_] := (x - conj[x])/(2 Sqrt[2]);

(*
{a, b}
*)

% // Simplify

(*
{ 1/2 ((a - Sqrt[2] b)^2 + (a + Sqrt[2] b)^2),
(-(a - Sqrt[2] b)^2 + (a + Sqrt[2] b)^2)/(2 Sqrt[2]) }
{a^2 + 2 b^2, 2 a b}
*)

(*
{3/10, -(1/5)}
*)


More generally, one can extend the definitions to numbers over an arbitrary quadratic extension of the rationals.

Clear[conj, rat, rad];
conj[x_, sqroot_: Sqrt[2]] := x /. sqroot -> -sqroot;
rat[x_, sqroot_: Sqrt[2]] := (x + conj[x, sqroot])/2;
rad[x_, sqroot_: Sqrt[2]] := (x - conj[x, sqroot])/(2 sqroot);

• Yes, of course. Very clever solution. Dec 4, 2014 at 17:09

You can use ToNumberField:

2/3 + 1/4 Sqrt[2]
ToNumberField[%, Sqrt[2]]


which produces

AlgebraicNumber[Sqrt[2], {2/3, 1/4}]

• Very nice. Thanks! Dec 4, 2014 at 15:39
• What if $a$ and $b$ are symbolic? Dec 4, 2014 at 15:41
• @TysonWilliams: I'm not sure how to handle that case, as I rarely use the abstract algebra functions. However, Daniel Lichtblau might know how to do it, so you could try asking him (or you could ask it as another question). Dec 4, 2014 at 15:48
• As a mathematician / theoretical computer scientist, I think of $a$ and $b$ as "symbolically rational" (i.e. some rational numbers by assumption). Of course I also know, but often forget, that (1) symbolic, (2) symbolically rational, and (3) and rational are three different "data types" that can all behave differently in Mathematica. Dec 4, 2014 at 16:18
• BTW: One can use ToNumberField[num][[2, 1]] to extract the rational part ("a") of any quadratic field. No need to even specify the generator! Feb 1, 2016 at 21:42