Trusted answers to developer questions

Gutha Vamsi Krishna

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 $\sqrt{-1}$.

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:

- Declaring it in the following way:

```
y = a+bim
```

where `a`

and `b`

are real numbers and `im`

is the imaginary part.

- Using the
, which accepts real numbers as parameters (`complex`

method`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 way x = 3+4im println(x) #declaring complex number usign Complex y = 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()`

functionsLet’s take a look at the following code snippet to understand it better.

#declaring complex number using normal way x = 3+4im # get real part from complex number r = real(x) println("Real part of x is $r") # get imaginary part from complex number i = 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 number y = 2//3 println(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 number x = 1/3 println(x) #representing rational number y = 1//3 println(y)

`num()`

and `den()`

functionsWe can get the numerator and denominator of a rational number using ** num()** and

`den()`

Let’s take a look at the following code snippet where we get the numerator and denominator from a rational number.

#declaring rational number y = 1//3 #display the numerator of a rational number println(numerator(y)) #display the denominator of a rational number println(denominator(y))

RELATED TAGS

julia

communitycreator

rationalnumbers

complexnumbers

CONTRIBUTOR

Gutha Vamsi Krishna

RELATED COURSES

View all Courses

Keep Exploring

Related Courses