What is the syntax for floor division in Julia? - julia

In Python 5//2 is a floor division.
In Julia:
5//2
Returns
5//2
How can I do floor division in Julia?

Try:
julia> 5 ÷ 2
2
The character ÷ can be entered by typing \div and pressing Tab.
On the other hand the operator // is used to create rational numbers.
The ÷ sign represents a div operator. If the number is negative you need to use fld to the the actual floor division. You could assign it to one of unused operators for comfortable use:
julia> ∺ = fld
fld (generic function with 10 methods)
julia> -5 ∺ 2
-3

You can also try:
julia> floor(5/2)
2.0
julia> floor(Int64, 5/2)
2
At the julia> prompt type '?' and then 'floor()' and again '? div()' to see what has already been mentioned.

In Julia, use fld:
julia> fld(5,2)
2
julia> fld(-5,2)
-3
julia> fld(5,-2)
-3
julia> fld(-5,-2)
2

Related

Evaluate vectors or tuples in a function (julia)

I want to evaluate a set of vectors (or tuples) in a function $f$ but Julia says me that is imposible.
For example: If I have an array of tuples p=[(1,1), (1,-1), (-1,1), (-1,-1)] and a function f(x,y)=x+y. I would like to calculate f(p[1]) = f(1,1)= 2. But Julia says me that the types are incompatible.
Can you help me please?
You have to splat a tuple like this:
julia> p=[(1,1), (1,-1), (-1,1), (-1,-1)]
4-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(1, -1)
(-1, 1)
(-1, -1)
julia> f(x,y)=x+y
f (generic function with 1 method)
julia> f(p[1]...)
2
you could also define a higher order function splat that would conveniently wrap any function and perform splatting. It is useful as then you can e.g. broadcast such function:
julia> splat(f) = x -> f(x...)
splat (generic function with 1 method)
julia> splat(f)(p[1])
2
julia> splat(f).(p)
4-element Array{Int64,1}:
2
0
0
-2
Alternatively you can define your function f like this:
julia> f((x,y),)=x+y
f (generic function with 1 method)
julia> f(p[1])
2
and now you do not have to do splatting.
Just use the ... operator to unpack the tuple as parameters:
julia> f(p[1]...)
2
In addition to other answers, if your task allows you, you can just define
julia> f(x) = f(x...)
and use it as
julia> f.(p)
4-element Vector{Int64}:
2
0
0
-2

I want to find the number which act to 0 of Julia - I mean the nearest number of 0

Why does this happen in Julia?
My input is
A = []
for i = 17:21
t = 1/(10^(i))
push!(A, t)
end
return(A)
And the output was:
5-element Array{Any,1}:
1.0e-17
1.0e-18
-1.1838881245526248e-19
1.2876178137472069e-19
2.5800991659088344e-19
I observed that
A[3]>0
false
I want to find the number which act to 0 of Julia, but I found this and don’t understand.
The reason for this problem is when you have i = 19, note that then:
julia> 10^19
-8446744073709551616
and it is unrelated to floating point numbers, but is caused by Int64 overflow.
Here is the code that will work as you expect. Either use 10.0 instead of 10 as 10.0 is a Float64 value:
julia> A=[]
Any[]
julia> for i=17:21
t=1/(10.0^(i))
push!(A,t)
end
julia> A
5-element Array{Any,1}:
1.0e-17
1.0e-18
1.0e-19
1.0e-20
1.0e-21
or using high precision BigInt type that is created using big(10)
julia> A=[]
Any[]
julia> for i=17:21
t=1/(big(10)^(i))
push!(A,t)
end
julia> A
5-element Array{Any,1}:
9.999999999999999999999999999999999999999999999999999999999999999999999999999967e-18
9.999999999999999999999999999999999999999999999999999999999999999999999999999997e-19
9.999999999999999999999999999999999999999999999999999999999999999999999999999997e-20
1.000000000000000000000000000000000000000000000000000000000000000000000000000004e-20
9.999999999999999999999999999999999999999999999999999999999999999999999999999927e-22
You can find more discussion of this here https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Overflow-behavior.
For example notice that (which you might find surprising not knowing about the overflow):
julia> x = typemin(Int64)
-9223372036854775808
julia> x^2
0
julia> y = typemax(Int64)
9223372036854775807
julia> y^2
1
Finally to find smallest positive Float64 number use:
julia> nextfloat(0.0)
5.0e-324
or
julia> eps(0.0)
5.0e-324

Which is better to use `Int((n+1)/2)`, `round(Int, (n+1)/2)` or `Int((n+1)//2)`?

I have a odd number n and want to use (n+1)/2 as an array index. What is the best way to calculate the index? I just came up with to use Int((n+1)/2), round(Int, (n+1)/2)) and Int((n+1)//2). Which is better or don't I need to too worry about them?
For better performance, you need integer division (div or ÷) for that. / gives floating point results for integer arguments. // gives a Rational not an integer. So you need to write div(n+1, 2) or (n+1) ÷ 2. To type ÷ you can write \div and then press TAB on julia REPL, Jupyter notebook, Atom, etc.
Even if the dividend (n+1) is even, you need integer division to obtain an integer result directly, otherwise you need to convert the result to integer which will in turn be costly compared to the integer division.
You may also use right bit shift operator >> or unsigned right bit shift operator >>>, as positive integer division by 2^n corresponds to shifting bits of that integer to the right n times. Although integer division by a power of 2 will be lowered to bit shift operation(s) by the compiler, the compiled code will still have an extra step if the dividend is a signed integer (i.e. Int and not UInt). Therefore, using the right bit shift operators instead may give better performance, although this is likely to be a premature optimization and affects the readability of your code.
The results of >> and >>> with negative integers will be different than that of the integer division (div).
Also note that using unsigned right bit shift operator >>> might save you from some integer overflow issues.
div(x, y)
÷(x, y)
The quotient from Euclidean division. Computes x/y, truncated to an
integer.
julia> 3/2 # returns a floating point number
1.5
julia> julia> 4/2
2.0
julia> 3//2 # returns a Rational
3//2
# now integer divison
julia> div(3, 2) # returns an integer
1
julia> 3 ÷ 2 # this is the same as div(3, 2)
1
julia> 9 >> 1 # this divides a positive integer by 2
4
julia> 9 >>> 1 # this also divides a positive integer by 2
4
# results with negative numbers
julia> -5 ÷ 2
-2
julia> -5 >> 1
-3
julia> -5 >>> 1
9223372036854775805
# results with overflowing (wrapping-around) argument
julia> (Int8(127) + Int8(3)) ÷ 2 # 127 is the largest Int8 integer
-63
julia> (Int8(127) + Int8(3)) >> 1
-63
julia> (Int8(127) + Int8(3)) >>> 1 # still gives 65 (130 ÷ 2)
65
You can use #code_native macro to see how things are compiled to native code. Please do not forget more instructions does not necessarily imply being slower, although here it is be the case.
julia> f(a) = a ÷ 2
f (generic function with 2 methods)
julia> g(a) = a >> 1
g (generic function with 2 methods)
julia> h(a) = a >>> 1
h (generic function with 1 method)
julia> #code_native f(5)
.text
; Function f {
; Location: REPL[61]:1
; Function div; {
; Location: REPL[61]:1
movq %rdi, %rax
shrq $63, %rax
leaq (%rax,%rdi), %rax
sarq %rax
;}
retq
nop
;}
julia> #code_native g(5)
.text
; Function g {
; Location: REPL[62]:1
; Function >>; {
; Location: int.jl:448
; Function >>; {
; Location: REPL[62]:1
sarq %rdi
;}}
movq %rdi, %rax
retq
nopw (%rax,%rax)
;}
julia> #code_native h(5)
.text
; Function h {
; Location: REPL[63]:1
; Function >>>; {
; Location: int.jl:452
; Function >>>; {
; Location: REPL[63]:1
shrq %rdi
;}}
movq %rdi, %rax
retq
nopw (%rax,%rax)
;}

Understanding Julia Int overflow behaviour

Coming from a Python / Matlab background, I'd like to understand better how Julia's Int64 overflow behaviour works.
From the documentation:
In Julia, exceeding the maximum representable value of a given type
results in a wraparound behavior.
julia> x = typemax(Int64)
9223372036854775807
julia> x + 1
-9223372036854775808
Now, I did some experiments with numbers obviously larger than typemax(Int64), but the behaviour I see isn't consistent with the documentation. It seems like things don't always just wrap around. Is only a single wraparound allowed?
julia> x = (10^10)^(10^10)
0
julia> x = 10^10^10^10
1 # ??
julia> x = 10^10^10^10^10
10 # I'd expect it to be 1? 1^10 == 1?
julia> x = 10^10^10^10^10^10
10000000000 # But here 10^10 == 10000000000, so now it works?
julia> typemax(Int64) > 10^19
true
julia > typemax(Int64) > -10^19
true
Can anyone shed light on the behaviour I am seeing?
EDIT:
Why does 9 overflow correctly, and 10 doesn't?
julia> 9^(10^14)
-1193713557845704703
julia> 9^(10^15)
4900281449122627585
julia> 10^(10^2)
0
julia> 10^(10^3)
0
Julia 0.5.0 (2016-09-19)
What you are seeing the result of PEMDAS order of operations, specifically the parenthesis before exponentiation portion. This effectively becomes a right-to-left solving of these expressions.
julia> 10^(10^10) #happens to overflow to 0
0
julia> 10^(10^(10^10)) # same as 10 ^ 0
1
julia> 10^(10^(10^(10^(10^10)))) # same as x = 10^(10^(10^(10^(10000000000)))) -> 10^(10^(10^(0))) -> 10^(10^(1)) -> 10^ 10
10000000000
So it's really just a matter of working through the arithmetic. Or realizing you are going to have such large operations that you start using BigInt from the outset.

Check size in bytes of variable using Julia

Question: How do I check the size in bytes of a variable using Julia?
What I've tried: In Matlab, the whos() function provided this information, but in Julia that just provides the variable names and module. Browsing the standard library in the Julia manual, sizeof() looked promising, but it only appears to provide the size of the canonical binary representation, rather than the current variable.
sizeof works on variables too
sizeof(a::Array{T,N})
returns the size of the array times the element size.
julia> x = [1 2 3 4]
1x4 Array{Int64,2}:
1 2 3 4
julia> sizeof(x)
32
julia> x = Int8[1 2 3 4]
1x4 Array{Int8,2}:
1 2 3 4
julia> sizeof(x)
4
sizeof(B::BitArray{N})
returns chunks; each chunk is 8 bytes so can represent up to 64 bits
julia> x = BitArray(36);
julia> sizeof(x)
8
julia> x = BitArray(65);
julia> sizeof(x)
16
sizeof(s::ASCIIString) and sizeof(s::UTF8String)
return the number of characters in the string (1 byte/char).
julia> sizeof("hello world")
11
sizeof(s::UTF16String) and sizeof(s::UTF32String)
Same as above but with 2 and 4 bytes/character respectively.
julia> x = utf32("abcd");
julia> sizeof(x)
16
Accordingly other strings
sizeof(s::SubString{ASCIIString}) at string.jl:590
sizeof(s::SubString{UTF8String}) at string.jl:591
sizeof(s::RepString) at string.jl:690
sizeof(s::RevString{T<:AbstractString}) at string.jl:737
sizeof(s::RopeString) at string.jl:802
sizeof(s::AbstractString) at string.jl:71
core values
returns the number of bytes each variable uses
julia> x = Int64(0);
julia> sizeof(x)
8
julia> x = Int8(0);
julia> sizeof(x)
1
julia> x = Float16(0);
julia> sizeof(x)
2
julia> x = sizeof(Float64)
8
one would expect, but note that Julia characters are wide characters
julia> sizeof('a')
4
getBytes
For cases where the layout is more complex and/or not contiguous. Here's a function that will iterate over the fields of a variable (if any) and return of sum of all of the sizeof results which should be the total number of bytes allocated.
getBytes(x::DataType) = sizeof(x);
function getBytes(x)
total = 0;
fieldNames = fieldnames(typeof(x));
if fieldNames == []
return sizeof(x);
else
for fieldName in fieldNames
total += getBytes(getfield(x,fieldName));
end
return total;
end
end
using it
create an instance of a random-ish type...
julia> type X a::Vector{Int64}; b::Date end
julia> x = X([i for i = 1:50],now())
X([1,2,3,4,5,6,7,8,9,10 … 41,42,43,44,45,46,47,48,49,50],2015-02-09)
julia> getBytes(x)
408
The function Base.summarysize provides exactly that
It also includes the overhead from the struct as seen in the examples.
julia> struct Foo a; b end
julia> Base.summarysize(ones(10000))
80040
julia> Base.summarysize(Foo(ones(10000), 1))
80064
julia> Base.summarysize(Foo(ones(10000), Foo(ones(10, 10), 1)))
80920
However, care should be taken as the function is non-exported and might not be future proof
In julia 1.6, varinfo() shows sizes:
julia> a = 1;
julia> v = ones(10000);
julia> varinfo()
name size summary
–––––––––––––––– ––––––––––– –––––––––––––––––––––––––––––
Base Module
Core Module
InteractiveUtils 250.022 KiB Module
Main Module
ans 78.164 KiB 10000-element Vector{Float64}
v 78.164 KiB 10000-element Vector{Float64}
a 8 bytes Int64
For specific variables, either use pattern matching (r"..." is a regular expression):
julia> varinfo(r"^v$")
name size summary
–––– –––––––––– –––––––––––––––––––––––––––––
v 78.164 KiB 10000-element Vector{Float64}
or combine the Base.summarysize from Korbinian answer with Base.format_bytes:
julia> pretty_summarysize(x) = Base.format_bytes(Base.summarysize(x))
pretty_summarysize (generic function with 1 method)
julia> pretty_summarysize(v)
"78.164 KiB"
Edit: beware that summarysize had a bug, at least in 1.5.3 and 1.6.1. varinfo was affected as well. It is fixed (tested with 1.7.3).

Resources