Hacker News new | past | comments | ask | show | jobs | submit login

You can try it out in Python directly which natively support complex numbers (just use j instead of i):

   >>> import math
   >>> z=1+2j
   >>> z*complex.conjugate(z)
   (5+0j)
   >>> math.sqrt((z*complex.conjugate(z)).real)
   2.23606797749979
   >>> abs(z)
   2.23606797749979
As we can see abs(z) does the right thing. Try it with a negative imaginary part too and "nicer" values:

   >> z = 3-4j
   >>> math.sqrt((z*complex.conjugate(z)).real)
   5.0
   >>> abs(z)
   5.0



Same in Julia, but no need to "import math", its already built in :D

    joe@zap:~ $ julia
                   _
       _       _ _(_)_     |  Documentation: https://docs.julialang.org    
      (_)     | (_) (_)    |
       _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
      | | | | | | |/ _` |  |
      | | |_| | | | (_| |  |  Version 1.10.5 (2024-08-27)
     _/ |\__'_|_|_|\__'_|  |
    |__/                   |

    julia> z=1+2*im
    1 + 2im

    julia> z*conj(z)
    5 + 0im

    julia> sqrt(z*conj(z))
    2.23606797749979 + 0.0im

    julia> abs(z)
    2.23606797749979


it isn't necessary in Python, either. GP is only importing it for square roots, but exponentiation (via the ** operator) by .5 works fine with complex numbers in Python as well. It even handles complex exponents (although you'd have to look up the branch cut semantics etc. in the documentation):

    >>> (1+1j)**(1+1j)
    (0.2739572538301211+0.5837007587586147j)
Ironically, the `math` library doesn't handle that:

    >>> math.pow(1+1j, 1+1j)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be real number, not complex


Definitely. I was mainly trying to avoid using `**` as non-Python users might be more familiar with '^' instead.


Works in Julia:

  julia> (1+im)^(1+im)
  0.2739572538301211 + 0.5837007587586147im


This is what made me fall in love with python. It's over now, but it was nice while it lasted.


Look the post on Common Lisp (SBCL interpreter) and you will see python as a toy language, as it has to import math :D


watch this:

  $ sbcl
  This is SBCL 2.4.8, an implementation of ANSI Common Lisp.
  * (setf z #C(1 2))
  #C(1 2)
  * (* z (conjugate z))
  5
  * (sqrt (* z (conjugate z)))
  2.236068
  * (abs z)
  2.236068


Conjugate is also a method:

  x=1
  x.conjugate()

  x=1+2j
  x.conjugate()




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: