1
$\begingroup$

We all know that

4^2 + 22^2 = 500

Is there a natural way to generates 500 from the complex number 4 + 22I ?

Two examples :

ex1) Abs[4 + 22I]^2 generates 500, but first Abs[4 + 22I] becomes (Sqrt[500])^2, then (10 Sqrt[5])^2, then 100*5, then 500. It generated 500 but did some unnecessary works.

Trace[Norm[4 + 22 I]^2]

{{{{{I,I},22 I,22 I},4+22 I,4+22 I},Norm[4+22 I],10 Sqrt[5]},(10 Sqrt[5])^2,100 5,500}

ex2) (Re[#]^2+Im[#]^2)&[4 + 22I] generates 500 but I believe there should be a built-in function.

The problem was about performance and naturality of the program.

Thanks to MichaelE2, there is a built-in function Internal`AbsSquare[] with good performance.

The below screenshot will help you understand everything.

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

This will help

$\endgroup$
9
  • 1
    $\begingroup$ Norm[4 + 22 I]^2 ? $\endgroup$
    – Syed
    Feb 16, 2022 at 9:28
  • 1
    $\begingroup$ (4 + 22 I)*Conjugate[4 + 22 I] or #*Conjugate[#] &[(4 + 22 I)]? $\endgroup$ Feb 16, 2022 at 9:44
  • $\begingroup$ Trace[Norm[4 + 22 I]^2] helps to understand what CPU had done. I guess (Re[#]^2+Im[#]^2)& or #*Conjugate[#] & are the best.. $\endgroup$
    – imida k
    Feb 16, 2022 at 10:05
  • 1
    $\begingroup$ Because of the performance. In my computer, Do[Norm[(5790570927 + 49802948104 I)]^2, 10000] takes 2.375 seconds while Do[# Conjugate[#] & (5790570927 + 49802948104 I), 10000] takes 0.015 seconds. $\endgroup$
    – imida k
    Feb 16, 2022 at 23:29
  • 1
    $\begingroup$ There is an answer but I can't post it: InternalAbsSquare[]` is faster than # Conjugate[#] & on my machine (mmv). (Did you mean Do[# Conjugate[#] & [5790570927 + 49802948104 I], 10000], because the code in your comment has a mistake?) $\endgroup$
    – Michael E2
    Feb 17, 2022 at 4:09

1 Answer 1

4
$\begingroup$

Using AbsoluteTiming is better than Timing, as for example, if the kernel splits the work among the 8 cores of computer, you may well get an answer that is 8 times longer than the time spent in real life (depending on OS details).

My first suggestion would have been Conjugate[#]#&. On my machine it is within 50% of Internal`AbsSquare. Whether the speed difference justifies using an undocumented function is a question for you and whether calculating the squared modulus is really the critical point in your application.

Do[(# Conjugate[#] &)[(5790570927 + 49802948104 I)], 10000] // AbsoluteTiming
(*{0.118674, Null}*)

Do[Internal`AbsSquare[(5790570927 + 49802948104 I)], 10000] // AbsoluteTiming
(* {0.07619, Null} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.