Skip to content

Commit cb66dc6

Browse files
Add Complex.real and Complex.imag (#15)
* Add Complex.real and Complex.imag This commit adds the Complex.real and Complex.imag functions, which return the real and imaginary part of a complex number respectively. * Conserve datatype if a number
1 parent 45b088b commit cb66dc6

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

lib/complex.ex

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,54 @@ defmodule Complex do
456456
r * r + i * i
457457
end
458458

459+
@doc """
460+
Returns the real part of the provided complex number.
461+
462+
### See also
463+
464+
`imag/1`
465+
466+
### Examples
467+
468+
iex> Complex.real(Complex.new(1, 2))
469+
1.0
470+
471+
iex> Complex.real(1)
472+
1
473+
"""
474+
@spec real(t) :: number
475+
@spec real(number) :: number
476+
def real(z)
477+
478+
def real(n) when is_number(n), do: n
479+
480+
def real(%Complex{re: r, im: _i}), do: r
481+
482+
@doc """
483+
Returns the imaginary part of the provided complex number.
484+
If a real number is provided, 0 is returned.
485+
486+
### See also
487+
488+
`real/1`
489+
490+
### Examples
491+
492+
iex> Complex.imag(Complex.new(1, 2))
493+
2.0
494+
495+
iex> Complex.imag(1)
496+
0
497+
"""
498+
499+
@spec imag(t) :: number
500+
@spec imag(number) :: number
501+
def imag(z)
502+
503+
def imag(n) when is_number(n), do: n * 0
504+
505+
def imag(%Complex{re: _r, im: i}), do: i
506+
459507
@doc """
460508
Returns a new complex that is the complex conjugate of the provided complex
461509
number.

test/complex_test.exs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ defmodule ComplexTest do
6363
assert_close Complex.abs_squared(b), 25
6464
assert_close Complex.abs_squared(c), 5
6565
assert_close Complex.abs_squared(d), 25
66+
assert Complex.real(a) == 1
67+
assert Complex.real(b) == 3.0
68+
assert Complex.real(c) == -1.0
69+
assert Complex.real(d) == 3.0
70+
assert Complex.imag(a) == 2.0
71+
assert Complex.imag(b) == 4.0
72+
assert Complex.imag(c) == 2.0
73+
assert Complex.imag(d) == -4.0
6674
assert_close Complex.phase(a), 1.1071487177940904
6775
assert_close Complex.conjugate(a), %Complex{re: 1.0, im: -2.0}
6876
assert_close Complex.square(a), Complex.multiply(a, a)
@@ -85,6 +93,14 @@ defmodule ComplexTest do
8593
assert_close Complex.abs_squared(b), 4
8694
assert_close Complex.abs_squared(c), 9
8795
assert_close Complex.abs_squared(d), 16
96+
assert Complex.real(a) == 1
97+
assert Complex.real(b) == 2
98+
assert Complex.real(c) == 3
99+
assert Complex.real(d) == 4
100+
assert Complex.imag(a) == 0
101+
assert Complex.imag(b) == 0
102+
assert Complex.imag(c) == 0
103+
assert Complex.imag(d) == 0
88104
assert_close Complex.phase(a), 0
89105
assert_close Complex.phase(-a), :math.pi()
90106
assert_close Complex.conjugate(a), a

0 commit comments

Comments
 (0)