Getting Started With Julia Programming Language: With Practical Implementation!

Akshay Last Updated : 29 Apr, 2024
9 min read

Introduction

Hello Readers!!
Walks like python. Runs like C
The above line explains to a ton why I decided to compose this article🤩. I went over Julia some time prior despite the fact that it was in its beginning phases, it was all the while making swells in the mathematical registering space.


Julia Programming Language is developed by MIT, a high-level language that has a syntax that is beginners friendly as Python and fast as C. This isn’t all, It gives distributed parallel execution, a sophisticated compiler, mathematical precision, and a broad numerical function library.


So in this blog, we are going to learn the basics of Julia Programming language with the help of code snippets. This article covers the basics of Julia, which helps you to give an overview on how to declare variables, how to use functions, and many more.
If you’re interested in Machine Learning in Julia, then checkout Start Machine Leaning With Julia: Top Julia Libraries For Machine Learning

If you’re interested in data visualization in Julia, then checkout Data Visualization In Julia Using Plots.jl: With Practical Implementation

julia Programming Language

This article was published as a part of the Data Science Blogathon.

What is Juila?

Julia is a high-level, high-performance programming language designed for numerical computing and scientific computing. It was created to address the needs of researchers, engineers, and scientists who require a language that’s both easy to use and fast in terms of execution speed. Julia combines the ease of use of dynamic languages like Python with the speed of compiled languages like C or Fortran.

One of Julia’s key features is its just-in-time (JIT) compilation, which allows it to achieve performance comparable to statically compiled languages while retaining the flexibility and interactivity of a dynamic language. Julia also has a sophisticated type system and multiple dispatch, which makes it particularly well-suited for mathematical and technical computing tasks.

Julia programs benefit from its growing community and ecosystem of packages. These packages cover various domains, including data science, scientific computing, and more. The Julia community actively develops and maintains these packages, ensuring a rich ecosystem for users.

Overall, Julia is gaining popularity in the scientific computing community for its performance and ease of use, especially in fields like data science, machine learning, computational biology, and computational physics. Its ability to seamlessly integrate with existing codebases and its extensive support for parallel and distributed computing further solidify its position as a go-to language for scientific computing.

Pros and Cons of Juila

Pros

High Performance: Julia is renowned for its high performance, often reaching levels comparable to C and Fortran. Its just-in-time (JIT) compilation and robust type system are key contributors to this speed.

Easy to Learn: Julia boasts an intuitive syntax, particularly for those with experience in other high-level programming languages like Python or MATLAB.

Dynamic Typing: Similar to Python, Julia supports dynamic typing, fostering flexibility and suitability for rapid prototyping and exploratory data analysis.

Multiple Dispatch: Julia’s innovative multiple dispatch system empowers developers to define and optimize functions for various combinations of argument types, enhancing code flexibility and expressiveness.

Interoperability: Julia seamlessly integrates with functions from other languages such as C, Fortran, and Python, making it an ideal choice for interfacing with existing workflows.

Growing Ecosystem: Julia’s ecosystem continues to expand rapidly, encompassing a broad spectrum of applications spanning from scientific computing to machine learning.

Cons:

Maturation: While Julia’s popularity is on the rise, it remains a relatively young language compared to stalwarts like Python or R. Consequently, its community and library support may not be as extensive.

Learning Curve for Performance Optimization: While Julia excels in performance by default, achieving peak optimization may necessitate a deeper understanding of its internals, posing a learning curve for some users.

Memory Usage: Julia’s performance enhancements sometimes come at the expense of increased memory usage when contrasted with languages like C or Fortran. This can be a concern, particularly when dealing with large datasets or memory-constrained systems.

IDE and Tooling: While there exist several IDEs and tools for Julia development, the ecosystem may not yet match the maturity or feature richness of those for more established languages.

Community and Support: Julia’s community is rapidly expanding, but it may not yet rival the size or longevity of communities for other languages. Consequently, users may encounter limitations in available support and resources.

Stability of APIs: Given Julia’s relative youth, there may be some volatility in APIs and packages as the language evolves, potentially necessitating updates to existing codebases.

Variables And Type

In this section, we will learn variables and their types and how to perform simple mathematical operations using Julia.

Variables

Variables

In programming, when we want to store the data we want a container to store it, the name of this container is called variable. When we want to store the data in a variable, we do this by writing the below code:

name = "Akshay"
number = 23
pie_value = 3.141

Here, the name is a string that contains a text value, a number contains an integer and pie_value is a floating number. Unlike C++, we don’t need to specify variable type before the variable name.

Print the variable

If you want to print the value of the variable, we use the print keyword. Check the below code to print the variable value:

>>> print(name)
   Akshay

Mathematical operations

In Julia, many mathematical operations are present which we can perform on variables. For example addition, multiplication, subtraction and many more.

a = 2
b = 3
sum = a + b
difference = a - b
product = a * b
quotient = b / a
power = a^3
modulus = b % a

Check the below image for all the mathematical operations that are available in Julia:

mathematical operations | julia

For complete information on mathematical operations check this link

Data Type

In Julia, every variable has its data type. There are many data types in Julia like Float, Int, String. Check the below image for all the data types that are available in Julia:

Data type | julia

If we want to determine the type of variable, then we use typeof function:

>>>typeof(0.2)
Float64
>>>typeof(50)
Int64
>>>typeof("Akshay")
String

For more information on variables and their types, check this Link.

Functions

These are the buildings blocks of Julia. All the operations that we perform on variables are carried out with the help of functions. These are also used to perform mathematical operations on variables. In a nutshell, a function is a kind of box that takes the input to perform some operations and then finally return an output. In this section, we will study function in great detail.

Functions

Defining functions

In Julia, the function starts with the function keyword and ends with the end.
function plus_two_number(x)
      #perform addition operation
        return x + 2
end

Note: Indentation is a must in Julia. As you can see in the above code in line number 2 and 3. Please note that there are not any fixed number of indentation spaces, but generally, four spaces are preferred.

 

An inline version of a function

We can also create an inline version of the function

plus_two_number(x) = x+2

Anonymous Functions

We use the lamdas function in Python, similarly, in Julia, we can create anonymous functions using the below code:
plus_two_number = x -> x+2

Void Functions

A function that takes no argument and returns no value is called a void function. Check the below code that doesn’t take any argument and print the Hello message.

function say_hello()
      println("Hello")
      return
end

Note: We can use println function also to print the output value but it adds a new line to the end of the output.

Optional Positional Arguments

We can also take a value from the user and pass it to the function. Check the below code which converts weight(in kg) on Earth to some other value on a different planet

function Weight_calc(weight_Earth, g=9.81)
      return weight_Earth*g/9.81
end

Check the output below:

>>>Weight_calc(60)
60
>>>Weight_calc(60, 3.72)
22.75

For more information on functions, check this link

Data Structures

In this section, we will discuss how we can store data in memory using different data structures. We will discuss vectors, tuples, named tuples, matrices and dictionaries.

Data structure | julia

Vectors

It is a list of ordered data which is having a common type (example Int, Any or Float) and it is a one-dimensional array. Check the below syntax to create a vector in Julia:

a = [1,2,3,4,5,6,7]
b = [1.2, 3,4,5,6]
c = ["Akshay", "Gupta", "xyz"]

Matrices

It is two-dimensional arrays. Check the below syntax to create a matrice in Julia

Matri_1 = [4,5,7; 8,1,3]

Tuples

It is a fixed size group of variables and may contain a common type of data but it is not compulsory. Once the tuple is created, you can not increase the size. Tuples are created using below syntax:

a = (1,2,3,4,5)
b = 1, 2, 3, 4, 5

So these can be created by using parenthesis or without using them.

Tuple_1 = (1, 2, 3, 4)
a, b, c, d= Tuple_1
>>>print("$a $b $c $d")
1 2 3 4

Named Tuples

They are the same as a tuple with a name identifier for a single value. Check below example for the named tuple:

>>> named_tuple = (a = 1, b = "hello")
(a = 1, b = "hello")
>>>named_tuple[:a]
1

Dictionaries

It is a collection of keys and values. They are unordered which means the order of key is not fixed. Check the below syntax to create a dictionary in Julia using the Dict keyword

Person_1 = Dict("Name" => "Akshay", "Phone" => 83659108, "Pant-size" => 40)
Person_2 = Dict("Name" => "Raju", "Phone" => 75973937, "Pant-size" => 36)
>>>print(Person_1[“Name”])
   Akshay

For more information on data structures in Julia, check this link

Control Flow

In this section of the blog, we will see control statements in Julia. First, we will start with conditional blocks for example if … else and after that, we will see how to perform looping using For and While Loops.

control flow | julia

If … else

I hope you must have studied about if else condition in C/C++. So, it uses to make decisions according to certain conditions.

For example, we want an absolute value of a number. It means we if the number that is passed is positive, then we will return the number itself. On the other hand, if it’s negative, then we will return the opposite if a number. Check the below code on how the if-else statements work.

function absolute_value(x)
    if x >= 0
        return x
    else
        return -x
    end
end

Note: You can see if-else block is ended with end, like a function

Check More Than One Condition

If you want to check more than two conditions, then we can use

  • and (written as &)
  • or (written as || )

Check the below code on how to use and condition

if 1 < 4 & 3 < 5
    print("Welcome!")
end

For Loops

If we want to iterate over a list of values and perform some operation then we can use it for loop in Julia. Check the below code to print the square of values from 1 to 10.

for j in 1:10
    println(j^2)
end

Output

1
4
9
16
25
36
49
64
81
100

While Loop

Check the below code of While loop in Julia

function while_loop()
    j=1
    while(j<20)
        println(j)
        j += 1
    end
end

Break

If we want to come out of the loop after a certain condition is met, use a Break keyword. Check the below code on how to use Break in Julia

for j in 1:10
    if j>3
        break
    else
        println(j^2)
    end
end

Continue

Check the below code on how to use the Continue keyword in Julia

for j in 1:20
    if j %2 == 0
        continue
    else
        println(j)
    end
end

For more information on iterators and control flow, check this link

How to Build a Countdown Timer in Julia ?

To create a countdown timer in Julia, you can utilize or use Julia Code the Dates module for handling time intervals. Begin by defining a function, let’s call it countdown_timer, which takes the duration of the countdown in seconds as its argument. Inside this function, initialize a variable, perhaps named remaining_time, to store the time remaining in the countdown. Then, enter a while loop that continues as long as there is time remaining (remaining_time > 0). Within the loop, use Dates.format to print the remaining time in the format “HH:MM:SS”. After displaying the time, use sleep(1) to pause execution for one second and then decrement the remaining_time variable by one. This loop will continue until the countdown reaches zero. Once the countdown is complete, print a message indicating that the time is up. Finally, you can call this function with the desired countdown duration as an argument to initiate the countdown timer. This example demonstrates how Julia , a new programming language tailored for scientific computing, can be a powerful tool for implementing algorithms like countdown timers with ease.

Conclusion

So in this article, we had a great detailed discussion on the Basics of Julia Programming Language. Hope you learn something from this blog and it will turn out best for your project. Thanks for reading and your patience. Good luck!

For more Blogs Related To Julia, Check below links:

Start Machine Leaning With Julia: Top Julia Libraries For Machine Learning

Data Visualization In Julia Using Plots.jl: With Practical Implementation

You can check my articles here: Articles

Email id: [email protected]

Connect with me on LinkedIn: LinkedIn

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details