I am trying to understand this code:
r = (1:10) - (4/1)
println(r)
Output:
-3.0:1.0:6.0
I understood why I got -3
and 6
. But why I got that value in the middle (1.0)? How does Julia calculate it? Or how I can google it?
Operators in Julia are the mathematical symbols that are used to perform operations on variables and values. These symbols are used to carry out arithmetic and logical computations. Variables on which the operators perform operations are termed as Operands.
Short-Circuit Evaluation The && and || operators in Julia correspond to logical “and” and “or” operations, respectively, and are typically used for this purpose.
The == is overloadable – it is a normal (for Julia) generic function with infix syntax. It has fallback definitions that give it useful default behavior on user-defined types, but you can change that as you see fit by adding new, more specific methods to == for your types.
The only unary operators in Julia are <: >: + - ! ~ ¬ √ ∛ ∜ , all of which are parsed as acting from the left. Edit: plus ' and . ' , of course, which are postfix operators. You can't define arbitrary new symbols as unary operators, only use/extend/redefine those that are already parsed that way.
(first:step:last)
syntax represent a Range
type in Julia
typeof(1:10) # => UnitRange{Int32}
If step part is omitted, by default it is assumed 1
1:10 == 1:1:10 # => true
A Range
is a compact view of a series
collect(1:10) # => 10-element Array{Int32,1}:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
So it's expected that a Range
type and a Vector
follow the same rules e.g when you add a constant value like this:
collect(1+(1:10))==collect(1:10)+1 # => true
or even adding two vectors give you the same result of adding their range representation like this:
collect((1:10)+(1:10))==collect(1:10)+collect(1:10) # => true
The division operator in 4/1
returns a Float64
. Although the original Range is a size 1 Int
step Range, after adding a floating point to both sides it becomes a Float64
Range. As such, a step size of 1.0 is created by converting the implicit integer step size (floating point numbers are non-uniformly distributed, so uniform stepping is a little tricky - sometimes there are rounding issues).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With