I want to sort a list (or in julia speak an one dimensional array) of complex numbers, by real part then by imaginary part of the complex number. I tried using anonymous function for the lt but it does not work.
julia> b=[3 + 1im,1 + 2im,1 + 1im,5 + 6im]
4-element Array{Complex{Int64},1}:
3 + 1im
1 + 2im
1 + 1im
5 + 6im
julia> sort(b,lt = x,y -> if(real(x)==real(y)) imag(x)<imag(y) else real(x)<real(y) end)
ERROR: UndefVarError: x not defined
Stacktrace:
[1] top-level scope at none:0
I want the following results
1 + 1im
1 + 2im
3 + 1im
5 + 6im
The imaginary part is the multiple of i. It is common practice to use the letter z to stand for a complex number and write z = a + bi where a is the real part and b is the imaginary part. where a is the real part and b is the imaginary part. Example State the real and imaginary parts of 3+4i.
There is no valid method to sort complex numbers. If you take two numbers and compare them, their squares should have the same relationship. Complex numbers can fail this. You can decide to ignore this and sort them anyway.
A complex number is the sum of a real number and an imaginary number. A complex number is expressed in standard form when written a + bi where a is the real part and bi is the imaginary part. For example, 5+2i 5 + 2 i is a complex number.
An complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and imaginary part can be represented by imag().
Approach: A complex number can be represented as Z = x + yi, where x is real part and y is imaginary. Time Complexity: In the above approach, as we are doing a constant number of operations regardless of the length of string, the time complexity is O (1)
Given a complex number Z, the task is to determine the real and imaginary parts of this complex number. Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.
Real part will be a substring starting from index 0 to a length (index of operator – 1) Imaginary part will be a substring starting from index (index of operator + 1) to (length of string – index of operator – 2)
So close!
julia> sort(b, lt = (x,y) -> real(x)==real(y) ? imag(x)<imag(y) : real(x)<real(y))
4-element Array{Complex{Int64},1}:
1+1im
1+2im
3+1im
5+6im
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With