# Taking Real, Im, and Abs of polynomial fractions

I want to find out real imaginary and Abs of polynomial fractions composed of real-valued variables.

For example, consider we have a polynomial fraction $$f=\dfrac{a_1 +b_1 i }{a_2 +b_2 i }$$ where $$a_{1,2}$$ and $$b_{1,2}$$ arereal valued variables (in fact, my actual values are again complecated fuctions of real-valued variables). (edit) Natual choice was to use inbuilt functions, but their output was as follows:

How can I simplify the real, imaginary, and using standard Mathematica function?

This is what I have so far, for example, for the Abs.

   Myabs[complex_] := Module[{Nreal, Nimag, Dreal, Dimag, real, imag},
Nreal = Numerator[complex] /. Complex[a_, b_] -> a;
Nimag = (Numerator[complex] - Nreal)/I;
Dreal = Denominator[complex] /. Complex[a_, b_] -> a;
Dimag = (Denominator[complex] - Dreal)/I;
real = (Nreal  Dreal + Nimag  Dimag)/(Dreal^2 + Dimag^2);
imag = (  Dreal Nimag -  Nreal Dimag)/(Dreal^2 + Dimag^2);
Sqrt[real^2 + imag^2]];


This function does the job for me so far. But I feel that there should be a better and straightforward way to do it.

• Would Re, Im, and Abs not work here? Can you give us an example where they fail but your function works, to see if maybe they can still be forced to work as you would like? Jan 5, 2020 at 19:25
• Thanks, @MarcoB. Of course, that was what I first tried. But the output was not as expected. Just edited the question with a screen capture.
– Pojj
Jan 5, 2020 at 19:40

Clear["Global*"]

expr = (a1 + I*b1)/(a2 + I*b2);


ComplexExpand will assume that all variables are real unless otherwise specified.

Abs[expr] // ComplexExpand[#, TargetFunctions -> {Re, Im}] &

(* Sqrt[a1^2 + b1^2]/Sqrt[a2^2 + b2^2] *)

Re[expr] // ComplexExpand[#, TargetFunctions -> {Re, Im}] & // Simplify

(* (a1 a2 + b1 b2)/(a2^2 + b2^2) *)

Im[expr] // ComplexExpand[#, TargetFunctions -> {Re, Im}] & // Simplify

(* (a2 b1 - a1 b2)/(a2^2 + b2^2) *)

• Perfect! It is the masterpiece I was looking for. What is really happening with Clear["Global*"]? (just to get better understanding)
– Pojj
Jan 5, 2020 at 19:49
• Clear["Global*"]` ensures that any prior definitions that might conflict are removed. Jan 5, 2020 at 19:51
• Got it! I should have asked this question long before! Thanks.
– Pojj
Jan 5, 2020 at 19:54