Julia can be used as a "pocket calculator". All the usual arithmetic operators and standard mathematical functions are available. Exponentiation is denoted by ^
. Mathematical constants such as e
or pi
are known. The imaginary unit \(\sqrt{-1}\) is denoted by im
.
Boolean operators &&
, ||
, and !
work as usual with true and false as logical constants. Boolean comparisons through ==
, <
, <=
, etc.
Comparisons chaining is supported. The end-of-line comment sign is #
; inline comments with #= ... =#
.
(1 + 2*3 + 3^4 + 4^5) / 10 # no integer division
sqrt(-1)
22 < pi^e < e^pi < 24 # chained comparison
Variable names consist of lower and upper case letters, digits, and underscore or (but start with a letter). UTF8 characters are allowed. Julia is case sensitive. A semicolon at the end suppresses printing on the console. When multiplying a variable with a number, the * sign can be left out.
γ = 0.57721_56649_01532_86; # Euler-Masceroni constant
2γ
Strings are written with ", character literals with '. The string function will change an object into its string representation. Strings are concatenated with * and duplicated with ^. String interpolation is done with the
"The result of e*pi is " * string(e*pi)
println("The result of pi*e is $(pi*e).")
Rational numbers are represented as m//n
and printed in their normalized, i.e. cancelled, form.
They are a subtype of floating point numbers and float(m//n)
will convert them to floats.
r = 1//3+ 1//6 + 1//12 + 1//15
1//3 - 1/3
BigFloat and BigInt examples
factorial(20)
Simple, one-line functions can be defined in a very intuitive way, e.g., f(x) = sin(x) + cos(x)
.
p(x) = 1 + 2x^2 + 3x^3; # a polynomial
p(1), p(1.0), p(1im) # returns a tupel
The type hierarchy of numerical types looks like this:
Number
Real
FloatingPoint
BigFloat
Float64 Float32 Float16
Integer
BigInt
Signed
Int128 Int64 Int32 Int16 Int8
--Int--
Unsigned
Uint128 Uint64 Uint32 Uint16 Uint8
Bool
Char
Rational
Complex
Vectors and matrices are defined in Julia in a very MATLAB-like way.Array{Float64,1}
v = [1, 2, 3, 4]
v[1], v[2:end]
A = [1.0 2 3 4; 5 6 7 8; 9 10 11 12]
H12 = [1/(i+j-1) for i in 1:12, j=1:12]
# det(H12)
w = A * v
A \ w