YD's blog

Posted 三 15 3月 2017

High Performance Programming 2

Variable Types

print_with_color(:red, "I love Julia!") # color change in terminal
I love Julia!

Types

typeof(Int64)
DataType
#Integers: Int8 to Int128
typemax(Int128)
170141183460469231731687303715884105727
typemin(Int8)
-128

Example of overflow

typemax(Int128)+1
-170141183460469231731687303715884105728
typemax(BigInt)
MethodError: no method matching typemax(::Type{BigInt})
Closest candidates are:
  typemax(::Type{Bool}) at bool.jl:12
  typemax(::Type{Int8}) at int.jl:314
  typemax(::Type{UInt8}) at int.jl:316
  ...
x=2
0 < x < 3
true
typeof(Float32);typeof(Float64)
DataType
typeof(0.1)
Float64
typeof(1/3)
Float64

Avoiding compare number with floating point numbers

0.1 + 0.2 == 0.3
false
# better using >= or <=
0.1 + 0.2 >= 0.3
true
# binary representation
bits(3)
"0000000000000000000000000000000000000000000000000000000000000011"

Assignments for different variables can be combined

a=1;b=2
c,d=b,a
c
typeof((c,d))
Tuple{Int64,Int64}

short-circuit In a && b, b is not evaluated when a is false In a || b, b is not evaluated when a is true (since || is already true)

n=1
n+=1
2
# complex number
println(typeof(3 + 4im))
abs(3+4im)
Complex{Int64}





5.0
# rationale number
println(typeof(3//4))
float(3//4)# convert to floating point number
num(3//4) # numerator
den(3//4) # denominator
Rational{Int64}





4
# single character
typeof('a')
Char
println("asdf\n","123\t","44455")
asdf
123 44455
#string
typeof("hello")
String

A String is a succession, or an array of characters (see the Ranges and arrays section)

str = "hello"
str[1]
'h'
length(str)
endof(str)
5
for c in str
    print(c)
end
hello
str[3:end]
"llo"
'A'=="A"
typeof('A')
typeof("A")
String
# string interpolation
a=3;b=2
"$a * $b = $(a*b)"
"3 * 2 = 6"
# concatenate string
x = string("adb","12345")
print(x)
adb12345

Strings prefixed with : are of type Symbol, such as :green They are more efficient than strings and are used for IDs or keys

print_with_color(:red, "I love Julia!")
I love Julia!
methodwith(String)
UndefVarError: methodwith not defined
replace("Julia","u","o")
"Jolia"
?replace
search: replace redisplay
replace(string, pat, r[, n])

Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text.

split("1,2,3,4",',')
4-element Array{SubString{String},1}:
 "1"
 "2"
 "3"
 "4"

Formatting numbers and strings

name = "Pascal"
x = @printf("Hello %s \n",name)
typeof(x)
Hello Pascal





Void

String as the return value

s = @sprintf("Hello %s \n",name)
typeof(s)
String

Regular expression

email_pattern = r".+@.+" # this pattern matches any string that contains @ somewhere in the middle
input = "john.doe@mit.edu"
println(ismatch(email_pattern, input)) #> true
true
email_pattern = r"(.+)@(.+)" # we want to capture this specific set of characters
input = "john.doe@mit.edu"
m = match(email_pattern, input)
println(m.captures) #> ["john.doe","mit.edu"]
Union{SubString{String},Void}["john.doe","mit.edu"]
m = match(r"(ju|l)(i)?(a)", "julia")
RegexMatch("lia", 1="l", 2="i", 3="a")
m.match
"lia"
replace("julia",r"u[\w]*l","red")
"jredia"
str = "the sky is blue"
reg = r"[\w]{3,}" # match more than three character
r = matchall(reg,str)
show(r)
SubString{String}["the","sky","blue"]
iter = eachmatch(reg,str)
for i in iter
    print(i)
end
RegexMatch("the")RegexMatch("sky")RegexMatch("blue")
# range
for i in 9:-2:1
    println(i)
end
9
7
5
3
1
# A one-dimensional array (also called a Vector in Julia)
a = split("A,B,C,D",",")
typeof(a) # Array{Type, n}, with n number of dimensions
Array{SubString{String},1}
# initialize array
arr = Float64[]
arr2 = [] # not good cuz 'Any' type
push!(arr,1.0)
show(arr)
[1.0]
# create array using range
arr = [1:7]
1-element Array{UnitRange{Int64},1}:
 1:7
workspace()
# create array with fixed size , improving performance
arr = Int64[]
sizehint!(arr, 1)
push!(arr,1)
push!(arr,2)
push!(arr,3)
show(arr)
[1,2,3]
arr = [100,37,50]
arr[1]
arr[end]
50
ndims(arr)
1
length(arr)
3
eltype(arr) # element type
Int64
size(arr,1)
3
?size
search: size sizeof sizehint! Csize_t resize! filesize Cssize_t trailingsize
size(A::AbstractArray, [dim...])

Returns a tuple containing the dimensions of A. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.

julia> A = ones(2,3,4);

julia> size(A, 2)
3

julia> size(A,3,2)
(4,3)

Collapse arr to string by ","

join(arr,",")
"100,37,50"
eqa = linspace(0,10,5)
println(join(eqa,','))
show(eqa)
0.0,2.5,5.0,7.5,10.0
linspace(0.0,10.0,5)
workspace()
arr = [1,2,3]
fill!(arr,0) # change element to a specific value
# A function whose name ends in a ! changes its first argument.
arr
3-element Array{Int64,1}:
 0
 0
 0

Change element type

v1 = rand(Int32,5)
println(typeof(v1))
v1 = round(Int64,v1)
print(typeof(v1))
Array{

Array appen

workspace()
b = [1:7]
c = [440,67]
append!(b,c) # ! change the first argument state, here is array 'b'
b
MethodError: Cannot `convert` an object of type Int64 to an object of type UnitRange{Int64}
This may have arisen from a call to the constructor UnitRange{Int64}(...),
since type constructors fall back to convert methods.



 in copy!(::Array{UnitRange{Int64},1}, ::Int64, ::Array{Int64,1}, ::Int64, ::Int64) at ./abstractarray.jl:593

 in append!(::Array{UnitRange{Int64},1}, ::Array{Int64,1}) at ./array.jl:494

A function whose name ends in a ! changes its first argument.

b = [1:7]
pop!(b)
push!(b,123)
shift!(b)
unshift!(b,42)
MethodError: Cannot `convert` an object of type Int64 to an object of type UnitRange{Int64}
This may have arisen from a call to the constructor UnitRange{Int64}(...),
since type constructors fall back to convert methods.



 in push!(::Array{UnitRange{Int64},1}, ::Int64) at ./array.jl:479

Remove element

b = [1:7]
splice!(b,3)
b
BoundsError: attempt to access 1-element Array{UnitRange{Int64},1} at index [3]



 in splice!(::Array{UnitRange{Int64},1}, ::Int64, ::Array{Any,1}) at ./array.jl:636 (repeats 2 times)

Check whether the element exist

b = [1:7]
println(in(42,b))
push!(b,42)
in(42,b)
false



MethodError: Cannot `convert` an object of type Int64 to an object of type UnitRange{Int64}
This may have arisen from a call to the constructor UnitRange{Int64}(...),
since type constructors fall back to convert methods.



 in push!(::Array{UnitRange{Int64},1}, ::Int64) at ./array.jl:479
# sort
b = [100,50,74,12,58]
println(sort(b))
println(b)
sort!(b)
println(b)
[12,50,58,74,100]
[100,50,74,12,58]
[12,50,58,74,100]
b = [20:30]
for e in b
    println("$e")
end
20:30
# operation
a = [1,2,3]
b = [4,5,6]
println(a .* b) # element wise computation with *
println(sum(a .* b))
dot(a,b) # same as sum(a .* b)
[4,10,18]
32





32

a and a1 point to the same object

a = [1,2,4,6]
a1 = a
show(a1) #> [1,2,4,6]
a[4] = 0
show(a) #> [1,2,4,0]
show(a1) #> [1,2,4,0]
[1,2,4,6][1,2,4,0][1,2,4,0]
# different object
a = [1,2,3,6]
b = copy(a)
4-element Array{Int64,1}:
 1
 2
 3
 6
# array to string
arr = ['a','b','c']
join(arr,"")
string(arr)
"['a','b','c']"
# calculate time
pt = time()
for i in 1:10^5
    i+(i-1)
end
time_elapsed = time() - pt
println("Time elapsed: $time_elapsed")
Time elapsed: 0.003777027130126953
#str time
println(time())
strftime(time())
1.489472573601163e9



UndefVarError: strftime not defined
# date
d = Date(2014,9,1)
println(d)
println(Dates.year(d))
println(Dates.month(d))
println(Dates.day(d))
2014-09-01
# datetime
DateTime(2014,9,1,12,30,59)
2014-09-01T12:30:59
# scope
# code in chapter 2\scope.jl
x = 1.0 # x is Float64

# y::Float64 = 1.0 # LoadError: "y is not defined"

function scopetest()
    x = 1 # now x is Int in local
    println(x) # 1, x is known here, because it's in local scope
    println("in",typeof(x))
    y::Float64 = 1.0 # y must be Float64, this is not possible in global scope
end
scopetest()
typeof(x)
1
inInt64





Float64
# compound expression
x = begin
    a = 5
    2 *a
end
println(x)
println(a)
10
5
# same as
workspace()
x = (a=5;2*a)
println(x)
println(a)
10
5

const variable with upperclass, value can be changed but type cannot

const GC = 6.67e-11 # gravitational constant in m3/kg s2   
# Use them whenever possible in the global scope.
# If you try to give a global constant a new value, you get a warning, but if you change its type
GC = 5.0
GC = 6
WARNING: redefining constant GC



invalid redefinition of constant GC
const ARR = [1,2,3]
ARR = [4,5,6]
println(ARR)
ARR = [4,5.0,6]
[4,5,6]


WARNING: redefining constant ARR



invalid redefinition of constant ARR
# a newspaper headline:
str = "The Gold and Blue Loses a Bit of Its Luster"
println(str)
nchars = length(str)
println("The headline counts $nchars characters") # 43 including space
str2 = replace(str, "Blue", "Red")
# strings are immutable
println(str) # The Gold and Blue Loses a Bit of Its Luster
println(str2)
println("Here are the characters at position 25 to 30:")
subs = str[25:30]
print("-$(lowercase(subs))-") # "-a bit -"
println("Here are all the characters:")
for c in str
    print(c)
end
The Gold and Blue Loses a Bit of Its Luster
The headline counts 43 characters
The Gold and Blue Loses a Bit of Its Luster
The Gold and Red Loses a Bit of Its Luster
Here are the characters at position 25 to 30:
-a bit -Here are all the characters:
The Gold and Blue Loses a Bit of Its Luster
# a newspaper headline:
str = "The Gold and Blue Loses a Bit of Its Luster"
println(str)
nchars = length(str)
println("The headline counts $nchars characters") # 43
str2 = replace(str, "Blue", "Red")
# strings are immutable
println(str) # The Gold and Blue Loses a Bit of Its Luster
println(str2)
println("Here are the characters at position 25 to 30:")
subs = str[25:30]
print("-$(lowercase(subs))-") # "-a bit -"
println("Here are all the characters:")
for c in str
    println(c)
end
arr = split(str,' ')
show(arr)                                                         #["The","Gold","and","Blue","Loses","a","Bit","of","Its","Luster"]
nwords = length(arr)
println("The headline counts $nwords words") # 10
println("Here are all the words:")
for word in arr
    println(word)
end
arr[4] = "Red"
show(arr) # arrays are mutable
println("Convert back to a sentence:")
nstr = join(arr, ' ')
println(nstr) # The Gold and Red Loses a Bit of Its Luster


# working with arrays:
println("arrays: calculate sum, mean and standard deviation ")
arr = [1:100]
typeof(arr) #>
println(sum(arr)) #> 5050
println(mean(arr)) #> 50.5
println(std(arr)) #> 29.011491975882016
The Gold and Blue Loses a Bit of Its Luster
The headline counts 43 characters
The Gold and Blue Loses a Bit of Its Luster
The Gold and Red Loses a Bit of Its Luster
Here are the characters at position 25 to 30:
-a bit -Here are all the characters:
T
h
e

G
o
l
d

a
n
d

B
l
u
e

L
o
s
e
s

a

B
i
t

o
f

I
t
s

L
u
s
t
e
r
SubString{String}["The","Gold","and","Blue","Loses","a","Bit","of","Its","Luster"]The headline counts 10 words
Here are all the words:
The
Gold
and
Blue
Loses
a
Bit
of
Its
Luster
SubString{String}["The","Gold","and","Red","Loses","a","Bit","of","Its","Luster"]Convert back to a sentence:
The Gold and Red Loses a Bit of Its Luster
arrays: calculate sum, mean and standard deviation 
100
1.0:1:1.0:100.0



MethodError: no method matching zero(::Type{UnitRange{Int64}})
Closest candidates are:
  zero(::Type{Base.LibGit2.Oid}) at libgit2/oid.jl:88
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuildItem}) at pkg/resolve/versionweight.jl:80
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuild}) at pkg/resolve/versionweight.jl:120
  ...



 in #var#951(::Bool, ::Void, ::Function, ::Array{UnitRange{Int64},1}) at ./statistics.jl:176

 in (::Base.#kw##var)(::Array{Any,1}, ::Base.#var, ::Array{UnitRange{Int64},1}) at ./<missing>:0

 in std(::Array{UnitRange{Int64},1}) at ./statistics.jl:220
Category: Julia
Tags: Julia