Skip to main content

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



Answer



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]);

Through[{rat, rad}[a + b Sqrt[2]]]
(*
{a, b}
*)

Through[{rat, rad}[(a + b Sqrt[2])^2]]
% // 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}
*)

Simplify@Through[{rat, rad}[(3 - 2 Sqrt[2])/10]]
(*
{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);

Comments