Monday, March 29, 2021

Introduction: Calculations, Variables, and Comments

This post's goal is to get some experience performing calculations using Julia. All these examples can be done in the REPL, but we'll use Jupyter here.

The first program that EVERYBODY writes in a new language is the so-called "Hello World" program. Who are WE to break with such a stupid time-honored tradition??

In [1]:
Hello, world!

Now that we got that bromide out of the way, lets do something a little more interesting!

Comments

In [2]:

Calculations

Here's how to perform some basic calculations - nothing that can't be done with a pocket calculator.

In [3]:
Out[3]:
-147.12
In [4]:
Out[4]:
-1061
In [5]:
Out[5]:
968
In [6]:
Out[6]:
0.21739130434782608
In [7]:
Out[7]:
343
In [8]:
Out[8]:
-1.5
In [9]:
Out[9]:
2.0
In [10]:
Out[10]:
-32.0
In [11]:
Out[11]:
6
In [12]:
Out[12]:
6
In [13]:
Out[13]:
2
In [14]:
Out[14]:
2

Variables

In [15]:
Out[15]:
2
In [16]:
Out[16]:
6
In [17]:
q = 6
In [18]:
In [19]:
q = 6
r = 2
In [20]:
Out[20]:
26
In [21]:
Out[21]:
26
In [22]:
Out[22]:
45

Trigonometric Functions and Some Constants

Julia has the usual trig, log and exponential functions built in, along with some constants

In [23]:
Out[23]:
0.0
In [24]:
Out[24]:
1.6197751905438615
In [25]:
In [26]:
Out[26]:
1.0
In [27]:
Out[27]:
π = 3.1415926535897...
In [28]:
Out[28]:
-1.0
In [29]:
Out[29]:
-0.7071067811865475
In [30]:

Log and Exponential Functions

In [31]:
Out[31]:
4.605170185988092
In [32]:
Out[32]:
2.0
In [33]:
Out[33]:
43.0
In [34]:
Out[34]:
ℯ = 2.7182818284590...
In [35]:
UndefVarError: e not defined

Stacktrace:
 [1] top-level scope
   @ :0
 [2] eval
   @ ./boot.jl:360 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1094

In [36]:
In [37]:
Out[37]:
23.0
In [38]:
Out[38]:
403.4287934927351
In [39]:
Out[39]:
403.4287934927351
In [ ]:

Roots

In [40]:
Out[40]:
1.4142135623730951
In [41]:
Out[41]:
1.2599210498948732

Rounding Functions

In [42]:
Out[42]:
3.0
In [43]:
Out[43]:
2.0
In [44]:
Out[44]:
6.0

GCD and LCM

In [45]:
Out[45]:
7
In [46]:
Out[46]:
98

Conclusion

So you get the idea:

  • Julia has a large number of built-in functions
  • There are some built-in constants like \pi and \euler
  • To store a calculation into a variable, do this: var = value
  • To output a variable called x, just type it or use println(x)
  • Single-line comments are started with a #
  • Multi-line comments are wrapped in #= and =#

For a list of the built-in functions, see this page: https://docs.julialang.org/en/v1/manual/mathematical-operations/

Another take-away from this introduction is that Jupyter allows you to experiment with your calculations - think of it as a playground. The advantage of Jupyter over the REPL is that you can easily save your work, share it with others, and etc.

No comments:

Post a Comment