In this shot, we will learn about complex and rational numbers in Julia.
A complex number is a number that can be expressed in the form of a+bi
, where a and b are real numbers and i is the imaginary part, meaning that i is .
In Julia, we represent a complex number as a+bim
, where a and b are real numbers and im is the imaginary part.
We can create a complex number in Julia using two ways:
y = a+bim
where a
and b
are real numbers and im
is the imaginary part.
complex
method, which accepts real numbers as parameters (a
, b
in the code below) and returns a complex number.complex(a,b)
Let’s look at an example of this.
#declaring complex number using normal wayx = 3+4imprintln(x)#declaring complex number usign Complexy = complex(4, 5)println(y)
real()
and imag()
functionsWe can get the real and imaginary parts of a complex number using the real()
and imag()
functions respectively.
Let’s take a look at the following code snippet to understand it better.
#declaring complex number using normal wayx = 3+4im# get real part from complex numberr = real(x)println("Real part of x is $r")# get imaginary part from complex numberi = imag(x)println("Imaginary part of x is $i")
A rational number is any number that can be expressed as the fraction p/q
of two integers.
In Julia, we represent a rational number in the p//q
format.
Let’s take a look at an example.
#declaring a rational numbery = 2//3println(y)
We use rational numbers in Julia where we feel that float numbers cannot be used. For example, dividing 1 with 3 returns 0.3333333333333333 ...
. When we don’t want to use this kind of result, then we can directly use the representation 1//3
for the rational number 1/3.
#representing float numberx = 1/3println(x)#representing rational numbery = 1//3println(y)
num()
and den()
functionsWe can get the numerator and denominator of a rational number using num()
and den()
, respectively.
Let’s take a look at the following code snippet where we get the numerator and denominator from a rational number.
#declaring rational numbery = 1//3#display the numerator of a rational numberprintln(numerator(y))#display the denominator of a rational numberprintln(denominator(y))