Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(x:y) operator in Julia

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?

like image 693
konstantin_doncov Avatar asked Oct 21 '15 10:10

konstantin_doncov


People also ask

What does the operator do in Julia?

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.

What does && mean in Julia?

Short-Circuit Evaluation The && and || operators in Julia correspond to logical “and” and “or” operations, respectively, and are typically used for this purpose.

Can I use == in Julia?

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.

What is a unary operator in Julia?

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.


2 Answers

(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
like image 53
Reza Afzalan Avatar answered Sep 29 '22 16:09

Reza Afzalan


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).

like image 29
Dan Getz Avatar answered Sep 29 '22 16:09

Dan Getz