Web-based interface for running Julia (which I'm using right now): install locally on your machine
Free web-based Julia service without installation (Julia may not be up-to-date)
Julia is a new programming language developed from 2009 (public appearance in 2012) by contributers (mostly are from MIT). It is designed for high-performance scientific computing.
It provides an alternative scientific language/platform to Matlab, and very appealing for implementing optimization algorithms: 0. open and free (MIT license)
The core of Julia is written in C/C++ with parsers in Scheme and JIT compilation in the LLVM compiler framework. Most of julia libraries are written in Julia itself.
versioninfo()
Julia Version 0.4.5 Commit 2ac304d (2016-03-18 00:58 UTC) Platform Info: System: Darwin (x86_64-apple-darwin13.4.0) CPU: Intel(R) Core(TM) i7-4650U CPU @ 1.70GHz WORD_SIZE: 64 BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell) LAPACK: libopenblas64_ LIBM: libopenlibm LLVM: libLLVM-3.3
println("Hello Julia")
Hello Julia
?print
search: print println print_joined print_escaped print_shortest print_unescaped
print(x)
Write (to the default output stream) a canonical (un-decorated) text representation of a value if there is one, otherwise call show
. The representation used by print
includes minimal formatting and tries to avoid Julia-specific details.
a = 3
typeof(a)
Int64
a = "a string"
typeof(a)
ASCIIString
a = 1e-7
typeof(a)
Float64
1 == true
true
0 == false
true
!true
false
a = -1
if a>0
println("positive")
elseif a<0
println("negative")
else
println("zero")
end
negative
if 1
println("true")
end
LoadError: TypeError: non-boolean (Int64) used in boolean context while loading In[14], in expression starting on line 1
function sphere_vol(r)
return 4/3*pi*r^3
end
sphere_vol (generic function with 1 method)
function sphere_vol(r)
4/3*pi*r^3
end
sphere_vol (generic function with 1 method)
r = 5
# print("sphere radius=%f, vol=%0.3f\n", r, sphere_vol(r))
@printf "sphere radius=%f, vol=%0.3f\n" r sphere_vol(r)
sphere radius=5.000000, vol=523.599
f(x) = sin(1 / x)
f(1/pi)
1.2246467991473532e-16
quad_root(a,b,c) = ((-b + sqrt(b^2-4a*c))/2a, (-b - sqrt(b^2-4a*c))/2a)
quad_root (generic function with 1 method)
soln = quad_root(2,4,1)
(-0.2928932188134524,-1.7071067811865475)
soln[1]
-0.2928932188134524
soln[:]
LoadError: MethodError: `getindex` has no method matching getindex(::Tuple{Float64,Float64}, ::Colon) Closest candidates are: getindex(::Tuple, !Matched::Int64) getindex(::Tuple, !Matched::Real) getindex(::Tuple, !Matched::AbstractArray{Bool,N}) ... while loading In[22], in expression starting on line 2
map(x -> sin(1 / x), randn(3)) # function without a name, apply a function on the elements of an array
3-element Array{Float64,1}: 0.721004 0.251543 0.841597
function f(x, y=2, z=3; a=1, b=.1, c=2) # default values, named arguments
return exp(cos(a * x + b))
end
f (generic function with 3 methods)
f(1, 2, 3, b=-1)
2.718281828459045
s = "3.1415"
f=0
gc()
f = float(s)
println(5f)
LoadError: invalid redefinition of constant f while loading In[97], in expression starting on line 2
i = parse(Int,s)
LoadError: ArgumentError: invalid base 10 digit '.' in "3.1415" while loading In[27], in expression starting on line 1 in tryparse_internal at /Applications/Julia-0.4.5.app/Contents/Resources/julia/lib/julia/sys.dylib (repeats 2 times) in parse at /Applications/Julia-0.4.5.app/Contents/Resources/julia/lib/julia/sys.dylib
c = 'α'
println(c, ", ascii value = ", Int(c))
α, ascii value = 945
str = "This is a string"
show(str[4:6])
"s i"
a = "welcome"
b = "julia"
c = 1
println("$a to $b in $c")
welcome to julia in 1
println("1 + 2 = $(1+2)")
1 + 2 = 3
a = "welcome"
b = "julia"
println(a * b) # string concatenation
welcomejulia
a^3
"welcomewelcomewelcome"
s = "The quick brown fox jumps over the lazy dog α,β,γ "
r = search(s, "brown")
11:15
r = replace(s, "brown", "red")
"The quick red fox jumps over the lazy dog α,β,γ "
r = search(s, r"b[\w]*n")
11:15
r = strip(s)
"The quick brown fox jumps over the lazy dog α,β,γ"
r = split("welcome, to, julia", [',', ' '], limit=0, keep=false)
3-element Array{SubString{ASCIIString},1}: "welcome" "to" "julia"
### Arrays
a = [1 2 3]
1x3 Array{Int64,2}: 1 2 3
a = [1,2,3]
3-element Array{Int64,1}: 1 2 3
a = [1;2;3]
3-element Array{Int64,1}: 1 2 3
a = Int64[]
push!(a, 4)
push!(a, 5)
tmp = push!(a,6)
show(tmp); println()
show(a)
[4,5,6] [4,5,6]
a = (Array{Int64, 1})[] # Array of Arrays
push!(a, [1,2,3])
push!(a, [4,5])
2-element Array{Array{Int64,1},1}: [1,2,3] [4,5]
a = [1 2 3]
A = repmat(a, 3, 2)
3x6 Array{Int64,2}: 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
a = ["Hi Im element # $(i+2*(j-1))" for i=1:2, j=1:3]
2x3 Array{ByteString,2}: "Hi Im element # 1" "Hi Im element # 3" "Hi Im element # 5" "Hi Im element # 2" "Hi Im element # 4" "Hi Im element # 6"
a[:,2]
2-element Array{ByteString,1}: "Hi Im element # 3" "Hi Im element # 4"
a[end,:]
1x3 Array{ByteString,2}: "Hi Im element # 2" "Hi Im element # 4" "Hi Im element # 6"
push!([1,2,3], 4, 5, 6)
6-element Array{Int64,1}: 1 2 3 4 5 6
append!([1,2,3], [4,5,6])
6-element Array{Int64,1}: 1 2 3 4 5 6
prepend!([3], [1,2])
3-element Array{Int64,1}: 1 2 3
insert!([1,2,3,4],2,10)
5-element Array{Int64,1}: 1 10 2 3 4
deleteat!([1,2,3,4],2:3)
2-element Array{Int64,1}: 1 4
function foo(arg::Int)
arg_local = arg
arg_local = 2
return (arg_local)
end
arg = 10
foo(arg)
show(arg)
10
function foo!(arg::Array)
arg_local = arg
arg_local[1] = 2
return (arg_local)
end
arg = [10 20]
foo(arg)
show(arg)
LoadError: MethodError: `isless` has no method matching isless(::Array{Int64,2}, ::Int64) Closest candidates are: isless(!Matched::AbstractFloat, ::Real) isless(!Matched::Real, ::Real) isless(!Matched::Char, ::Integer) ... while loading In[55], in expression starting on line 8
A = ones(3,3)
3x3 Array{Float64,2}: 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
B = A
A[2,2] = -1
B
3x3 Array{Float64,2}: 1.0 1.0 1.0 1.0 -1.0 1.0 1.0 1.0 1.0
B = copy(A)
3x3 Array{Float64,2}: 1.0 1.0 1.0 1.0 -1.0 1.0 1.0 1.0 1.0
x = ("foo", "bar")
typeof(x)
Tuple{ASCIIString,ASCIIString}
x = "foo", "bar"
word1, word2 = x # unpacking
show(word1); println()
show(word2)
"foo" "bar"
x = ("foo", "bar")
x[1]
#x[1] = "xxx"
#show(x)
"foo"
x = ["foo" "bar"]
x[1] = "xxx"
show(x)
ASCIIString["xxx" "bar"]
d = Dict{Any,Any}(2=>"two", 1=>"one", 4=>"four", 3=>"three")
Dict{Any,Any} with 4 entries: 4 => "four" 2 => "two" 3 => "three" 1 => "one"
# alternatively,
d = Dict(2=>"two", 1=>"one", 4=>"four", 3=>"three")
Dict{Int64,ASCIIString} with 4 entries: 4 => "four" 2 => "two" 3 => "three" 1 => "one"
show(keys(d)); println()
show(values(d))
[4,2,3,1] ASCIIString["four","two","three","one"]
for k in sort(collect(keys(d)))
if(k == 1) continue
end
if(k == 4) break
end
print(k, ": ", d[k], ", ")
end
2: two, 3: three,
show(d[3])
d[3] = "not three"
show(d[3])
"three""not three"
d[0] = "zero"
"zero"
show(d)
1 in keys(d)
Dict(0=>"zero",4=>"four",2=>"two",3=>"not three",1=>"one")
true
"one" in values(d)
true
animals = ["dog", "cat", "bird"]; # semicolon suppresses output
plurals = [animal * "s" for animal in animals]
3-element Array{ByteString,1}: "dogs" "cats" "birds"
a = [i+j for i=1:2, j=1:3]
2x3 Array{Int64,2}: 2 3 4 3 4 5
["$i" => i for i in 1:3]
Dict{ASCIIString,Int64} with 3 entries: "1" => 1 "2" => 2 "3" => 3
d = [i => @sprintf("str%d", i) for i=1:10]
Dict{Int64,ByteString} with 10 entries: 7 => "str7" 4 => "str4" 9 => "str9" 10 => "str10" 2 => "str2" 3 => "str3" 5 => "str5" 8 => "str8" 6 => "str6" 1 => "str1"
for i in 1:5 # iteration over a range 1:5, "for i = 1:5" also works
print(i, ", ")
end
1, 2, 3, 4, 5,
for i in collect(1:5) # iteration over an array
print(i, ", ")
end
1, 2, 3, 4, 5,
a = collect(1:2:10)
while !isempty(a)
print(pop!(a), ", ")
end
9, 7, 5, 3, 1,
countries = ("Japan", "Korea", "China")
cities = ("Tokyo", "Seoul", "Beijing")
for (country, city) in zip(countries, cities) # zip()
println("The capital of $country is $city")
end
The capital of Japan is Tokyo The capital of Korea is Seoul The capital of China is Beijing
countries = ("Japan", "Korea", "China")
cities = ("Tokyo", "Seoul", "Beijing")
for (i, country) in enumerate(countries) # above example, with index
city = cities[i]
println("The capital of $country is $city")
end
The capital of Japan is Tokyo The capital of Korea is Seoul The capital of China is Beijing
type Person
name::AbstractString
age::Float64
children::Array{AbstractString, 1}
# constructor
Person(name::AbstractString, age) = new(name, age, [])
Person(name::AbstractString, age, children) = new(name, age, children)
end
p1 = Person("Julia", 4)
p2 = Person("Steve", 42, ["Anna", "Bob"])
show(p1); println()
show(p2)
Person("Julia",4.0,AbstractString[]) Person("Steve",42.0,AbstractString["Anna","Bob"])
people = Person[]
push!(people, Person("Steve", 42))
1-element Array{Person,1}: Person("Steve",42.0,AbstractString[])
fname = "benchmarks.csv"
open(fname, "r") do f
for line in eachline(f)
print(line)
end
end
c,fib,0.046968 c,mandel,0.406981 c,parse_int,0.187874 c,pi_sum,46.528101 c,printfd,22.814035 c,quicksort,0.516176 c,rand_mat_mul,236.536026 c,rand_mat_stat,11.954784 fortran,fib,.032889 fortran,mandel,.299340 fortran,parse_int,.917261 fortran,pi_sum,46.140000 fortran,quicksort,.676291 fortran,rand_mat_mul,1119.072000 fortran,rand_mat_stat,13.744000 go,fib,0.10060900000000002 go,mandel,0.404544 go,parse_int,0.708133 go,pi_sum,61.80803100000001 go,quicksort,0.5738630000000001 go,rand_mat_mul,2325.240173 go,rand_mat_stat,106.68269000000001 java,fib,0.042393 java,mandel,0.231601 java,parse_int,1.043216 java,pi_sum,46.616215 java,printfd,119.493350 java,quicksort,0.871698 java,rand_mat_mul,555.709576 java,rand_mat_stat,47.901065 java,sinc_sum,0.155235 javascript,fib,0.175 javascript,mandel,0.632 javascript,parse_int,0.438 javascript,pi_sum,102.1 javascript,quicksort,1.5 javascript,rand_mat_mul,4067 javascript,rand_mat_stat,39.7 julia,fib,0.112414 julia,mandel,0.293425 julia,parse_int,0.362631 julia,pi_sum,49.372756 julia,printfd,45.527162 julia,quicksort,0.640893 julia,rand_mat_mul,261.875685 julia,rand_mat_stat,25.633835 lua,fib,0.112 lua,mandel,0.287 lua,parse_int,1.276 lua,pi_sum,55.045 lua,quicksort,1.217 lua,rand_mat_mul,339.773 lua,rand_mat_stat,51.834 mathematica,fib,7.676 mathematica,mandel,2.54 mathematica,parse_int,3.317 mathematica,pi_sum,70.181 mathematica,quicksort,24.885 mathematica,rand_mat_mul,285.801 mathematica,rand_mat_stat,80.199 matlab,fib,217.85100000 matlab,mandel,20.84800000 matlab,parse_int,296.93900000 matlab,pi_sum,59.23900000 matlab,printfd,2446.41600000 matlab,quicksort,28.09500000 matlab,rand_mat_mul,279.38000000 matlab,rand_mat_stat,125.26700000 octave,fib,458.62197876 octave,mandel,159.23213959 octave,parse_int,1710.93678474 octave,pi_sum,13005.94305992 octave,printfd,2002.40898132 octave,quicksort,911.63611412 octave,rand_mat_mul,295.38583755 octave,rand_mat_stat,429.40402031 python,fib,3.75509262085 python,mandel,4.958152771 python,parse_int,2.30002403259 python,pi_sum,787.712097168 python,quicksort,17.1549320221 python,rand_mat_mul,294.181108475 python,rand_mat_stat,227.633953094 r,fib,26.00000000 r,mandel,22.00000000 r,parse_int,10.00000000 r,pi_sum,770.00000000 r,quicksort,132.00000000 r,rand_mat_mul,452.00000000 r,rand_mat_stat,199.00000000
f = open(fname, "r")
showall(readlines(f))
close(f)
LoadError: invalid redefinition of constant f while loading In[83], in expression starting on line 1
using DataFrames
using Gadfly # ggplot2 style plots
benchmarks = readtable("benchmarks.csv", names=[:language, :benchmark, :time])
# show(benchmarks)
cdata = benchmarks[benchmarks[:language].== "c", :]
# show(cdata)
benchmarks = join(benchmarks, cdata, on=:benchmark)
# show(benchmarks)
benchmarks[:time]./= benchmarks[:time_1]
#benchmarks[:language] = PooledDataArray(benchmarks[:language])
#benchmarks[:benchmark] = PooledDataArray(benchmarks[:benchmark])
benchmarks = benchmarks[benchmarks[:language].!= "c", :]
#benchmarks[:language] = setlevels!(benchmarks[:language], Dict{UTF8String,Any}(benchmarks[:language],
# [ lang == "javascript" ? "JavaScript" : ucfirst(lang) for lang in benchmarks[:language]]));
benchmarks
language | benchmark | time | language_1 | time_1 | |
---|---|---|---|---|---|
1 | fortran | mandel | 0.7355134514879074 | c | 0.406981 |
2 | go | mandel | 0.9940120054744571 | c | 0.406981 |
3 | java | mandel | 0.569070792002575 | c | 0.406981 |
4 | javascript | mandel | 1.5528980468375675 | c | 0.406981 |
5 | julia | mandel | 0.7209796034704323 | c | 0.406981 |
6 | lua | mandel | 0.7051926256999712 | c | 0.406981 |
7 | mathematica | mandel | 6.241077593302882 | c | 0.406981 |
8 | matlab | mandel | 51.22597860833798 | c | 0.406981 |
9 | octave | mandel | 391.25202304284477 | c | 0.406981 |
10 | python | mandel | 12.182762269000273 | c | 0.406981 |
11 | r | mandel | 54.05657757978874 | c | 0.406981 |
12 | fortran | parse_int | 4.882320065575865 | c | 0.187874 |
13 | go | parse_int | 3.769191053578462 | c | 0.187874 |
14 | java | parse_int | 5.5527427957035025 | c | 0.187874 |
15 | javascript | parse_int | 2.331349734396457 | c | 0.187874 |
16 | julia | parse_int | 1.9301819304427432 | c | 0.187874 |
17 | lua | parse_int | 6.791785984223469 | c | 0.187874 |
18 | mathematica | parse_int | 17.655449929207872 | c | 0.187874 |
19 | matlab | parse_int | 1580.5220520135836 | c | 0.187874 |
20 | octave | parse_int | 9106.831092860108 | c | 0.187874 |
21 | python | parse_int | 12.242375382383937 | c | 0.187874 |
22 | r | parse_int | 53.22716288576386 | c | 0.187874 |
23 | fortran | pi_sum | 0.9916587827214354 | c | 46.528101 |
24 | go | pi_sum | 1.3284021843057814 | c | 46.528101 |
25 | java | pi_sum | 1.0018937802769985 | c | 46.528101 |
26 | javascript | pi_sum | 2.1943728156883084 | c | 46.528101 |
27 | julia | pi_sum | 1.0611384290108896 | c | 46.528101 |
28 | lua | pi_sum | 1.1830484979389122 | c | 46.528101 |
29 | mathematica | pi_sum | 1.5083572828386012 | c | 46.528101 |
30 | matlab | pi_sum | 1.2731875732474016 | c | 46.528101 |
⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ |
p = plot(benchmarks,
x = :language,
y = :time,
color = :benchmark,
Scale.y_log10,
Guide.ylabel(nothing),
Guide.xlabel(nothing),
Theme(
default_point_size = 1mm,
guide_title_position = :left,
colorkey_swatch_shape = :circle,
minor_label_font = "Georgia",
major_label_font = "Georgia",
),
)
draw(SVG(8inch,8inch/golden), p)
# Pkg.add("Winston")
import Winston # Matlab style plotting
# Winston.figure(width=600, height=400)
x = collect(-2pi:.01:2pi)
pl = Winston.plot(x, cos(x))
WARNING: deprecated syntax "AbstractVecOrMat{T} (" at /Users/sklee/.julia/v0.4/Winston/src/Winston.jl:96. Use "AbstractVecOrMat{T}(" instead. WARNING: requiring "Dates" in module "Winston" did not define a corresponding module. WARNING: module Winston should explicitly import * from Base
import PyPlot # Julia interface to Matplotlib, a powerful python plotting library
x = linspace(0,2*pi,1000); y = sin(3*x + 4*cos(2*x));
PyPlot.plot(x, y, color="red", linewidth=2.0, linestyle="--")
PyPlot.title("A sinusoidally modulated sinusoid")
PyObject <matplotlib.text.Text object at 0x3230ec690>
Pkg.available()
916-element Array{AbstractString,1}: "AbstractDomains" "Accumulo" "ActiveAppearanceModels" "Actors" "AffineTransforms" "AmplNLWriter" "Anasol" "AndorSIF" "AnsiColor" "AppConf" "AppleAccelerate" "ApproxFun" "Arbiter" ⋮ "XMLDict" "XSim" "XSV" "YAML" "Yelp" "Yeppp" "YT" "ZChop" "ZipFile" "Zlib" "ZMQ" "ZVSimulator"
Pkg.add("Calculus")
Pkg.update()
INFO: Nothing to be done INFO: METADATA is out-of-date — you may not have the latest version of Calculus INFO: Use `Pkg.update()` to get the latest versions of your packages INFO: Updating METADATA... INFO: Updating Plotly... INFO: Computing changes... INFO: No packages to install, update or remove
using Calculus
derivative(x -> sin(x), 1.0)
0.5403023058631036
import Calculus
Calculus.derivative(x -> sin(x), 1.0)
0.5403023058631036
using Images
using ImageMagick
using QuartzImageIO
const ϕ = golden
function foo(z)
c = (φ-2)+(φ-1)im
max = 80
for n = 1:max
abs(z) ≥ 2 && return n-1
z = z^2 + c
end
return max
end
foo(x, y) = foo(x + y*im)
foo_grid(n) =
broadcast(foo,
linspace(-0.5, 1, n)',
linspace(-1, 0.5, n))
convert(Image, scale(foo_grid(500), 1/80))
nheads = @time @parallel (+) for i=1:100000000
rand(Int)
end
1.029369 seconds (107.41 k allocations: 4.519 MB)
2500294072031143045
f(x) = x*x
code_llvm(f, (Float64,))
define double @julia_f_25995(double) { top: %1 = fmul double %0, %0 ret double %1 }
code_native(f, (Float64,))
.section __TEXT,__text,regular,pure_instructions Filename: In[95] Source line: 1 pushq %rbp movq %rsp, %rbp Source line: 1 mulsd %xmm0, %xmm0 popq %rbp ret
(http://docs.julialang.org/en/release-0.4/manual/noteworthy-differences/)