juliaref.txt 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. Julia Reference
  2. Julia Documentation - https://docs.julialang.org/en/v1/
  3. Julia by Examples - https://juliabyexample.helpmanual.io/
  4. The fast track to Julia - https://juliadocs.github.io/Julia-Cheat-Sheet/
  5. Julia Plots - https://docs.juliaplots.org/
  6. Julia Community (Standards) - https://julialang.org/community/standards/
  7. Julia Data Science - https://juliadatascience.io/
  8. Plotting with Makie - https://docs.makie.org/stable/
  9. Numerical Computing in Julia -
  10. https://www.matecdev.com/posts/julia-tutorial-science-engineering.html
  11. Julia interface to Gnuplot - https://gcalderone.github.io/Gnuplot.jl/
  12. Gaston Julia package for plotting - https://mbaz.github.io/Gaston.jl/stable/
  13. Introduction to Julia's Debugger -
  14. https://webpages.csus.edu/fitzgerald/julia-debugger-tutorial/
  15. Julia Mathematics - https://docs.julialang.org/en/v1/base/math/#Base.ceil
  16. A Deep Introduction to Julia for Data Science and Scientific Computing -
  17. http://ucidatascienceinitiative.github.io/IntroToJulia/
  18. Julia SOS - https://www.juliasos.com/
  19. Profile Julia code - https://opensourc.es/blog/constraint-solver-profiling/
  20. Parallel processing in Julia - https://berkeley-scf.github.io/tutorial-parallelization/parallel-julia
  21. # Julia-1.9.2 Current Stable version installation
  22. $ wget julia-1.9.2-linux-x86_64.tar.gz
  23. $ tar -xzvf julia-1.9.2-linux-x86_64.tar.gz
  24. $ mv julia-1.9.2/ ~/.julia/
  25. $ set path in ~/.bashrc [export PATH="$PATH:/home/saran/.julia/bin"]
  26. $ source .bashrc
  27. # upgrade julia-1.9.2 to julia-1.9.3 [https://julialang.org/downloads/]
  28. 1. download current stable release: v1.9.3 [Generic Linux on x86 - 64-bit (glibc)]
  29. $ wget https://julialang-s3.julialang.org/bin/linux/x64/1.9/julia-1.9.3-linux-x86_64.tar.gz
  30. 2. untar julia-1.9.3-linux-x86_64.tar.gz
  31. $ tar -xzvf julia-1.9.3-linux-x86_64.tar.gz
  32. 3. move julia-1.9.3/ to ~/.julia-1.9.3/
  33. $ mv downloads/julia-1.9.3/ .julia-1.9.3/
  34. 4. move directories compiled/ environments/ logs/ packages/ registries/ scratchspaces/
  35. $ mv ~/.julia-1.9.2/compiled/ ~/.julia-1.9.3/
  36. $ mv ~/.julia-1.9.2/environments/ ~/.julia-1.9.3/
  37. $ mv ~/.julia-1.9.2/logs/ ~/.julia-1.9.3/
  38. $ mv ~/.julia-1.9.2/packages/ ~/.julia-1.9.3/
  39. $ mv ~/.julia-1.9.2/registries/ ~/.julia-1.9.3/
  40. $ mv ~/.julia-1.9.2/scratchspaces/ ~/.julia-1.9.3/
  41. 5. remove ~/.julia-1.9.2
  42. $ rm -rf .julia/
  43. 6. rename ~/.julia-1.9.3 to ~/.julia/
  44. $ mv ~/.julia-1.9.3/ ~/.julia/
  45. 7. activate virtual environment, check status and update
  46. $ source .venv/dsci/bin/activate
  47. (@v1.9) pkg> status
  48. (@v1.9) pkg> update
  49. # Types - https://docs.julialang.org/en/v1/manual/types/
  50. # Arrays - https://docs.julialang.org/en/v1/base/arrays/
  51. # Mathematical operations and Elementary functions -
  52. https://docs.julialang.org/en/v1/mathematical-operations/
  53. # concise tutorial - https://syli.gitbook.io/julia-language-a-concise-tutorial/
  54. # random num - www.juliabloggers.com/basics-of-generating-random-numbers-in-julia/
  55. $ julia
  56. > versioninfo()
  57. > using Pkg
  58. > Pkg.add("package_name")
  59. # update julia to latest stable version
  60. (@v1.8) pkg> add UpdateJulia
  61. julia> using UpdateJulia
  62. julia> update_julia()
  63. Ref: https://stackoverflow.com/questions/30555225/how-to-upgrade-julia-to-a-new-release
  64. # remove broken link if already present
  65. cd .local/bin/
  66. rm julia
  67. rm julia-1.8
  68. rm julia-1.8.2
  69. # create symbolic link
  70. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia
  71. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia-1.8
  72. ln -s /home/saran/.julia/bin/julia /home/saran/.local/bin/julia-1.8.2
  73. # in the Julia REPL, hit ] to enter package mode and then enter
  74. (@v1.8) pkg> help
  75. (@v1.8) pkg> status
  76. (@v1.8) pkg> status --outdated
  77. (@v1.8) pkg> update
  78. (@v1.8) pkg> add <package>
  79. (@v1.8) pkg> rm <package>
  80. # the julia internal variable Sys.WORD_SIZE indicates
  81. # whether the target system is 32-bit or 64-bit
  82. Sys.WORD_SIZE
  83. # to quit
  84. exit()
  85. # Source Installation
  86. sudo apt-get install libncurses-dev libncurses5-dev libtinfo-dev
  87. git clone git://github.com/JuliaLang/julia.git
  88. cd julia
  89. make
  90. ... go take a long nap ...
  91. git pull && make (to upgrade Julia)
  92. # virtual environment
  93. pkg> add VirtualEnv
  94. $ mkdir .venv
  95. $ venv -h # display help
  96. $ venv --prompt dsci .venv/dsci/ # creating virtual environment with prompt name (dsci)
  97. $ source .venv/dsci/bin/activate # activating virtual environment
  98. $ deactivate # deactivating environment
  99. note: if above method of creating virtual environment not work then
  100. pkg> add Comonicon
  101. pkg> add VirtualEnv
  102. $ mkdir .venv
  103. $ julia -e 'using VirtualEnv; venv("/home/user/.venv/dsci")'
  104. $ source .venv/dsci/bin/activate
  105. $ deactivate
  106. Reference: Documentataion - https://mehalter.github.io/VirtualEnv.jl/stable/
  107. # load a file into the julia console
  108. > include('program.jl')
  109. # time function
  110. @time function(x)
  111. # import benchmark library
  112. using BenchmarkTools
  113. # benchmark function
  114. @benchmark function(x)
  115. # benchmark function with time tolerance
  116. @benchmark function() seconds=1 time_tolerance=0.01
  117. @benchmark function(x) seconds=1 time_tolerance=0.01
  118. # print the minimum time and memory allocation
  119. @btime function(x)
  120. # print minimum time in seconds
  121. @belapsed function(x)
  122. # import profiling library
  123. using Profile
  124. # profile function
  125. @profile function(x)
  126. # print the results
  127. Profile.print()
  128. # clear the profile results
  129. Profile.clear()
  130. # numerical type hierarchy
  131. Number
  132. |
  133. |----- Complex
  134. |----- Real
  135. |----- AbstractFloat
  136. | |_____ BigFloat
  137. | |_____ Float16
  138. | |_____ Float32
  139. | |_____ Float64
  140. |
  141. |----- AbstractIrrational
  142. | |_____ Irrational
  143. |
  144. |----- Integer
  145. | |
  146. | |----- Bool
  147. | |
  148. | |----- Signed
  149. | | |_____ BigInt
  150. | | |_____ Int128
  151. | | |_____ Int16
  152. | | |_____ Int32
  153. | | |_____ Int64
  154. | | |_____ Int8
  155. | |
  156. | |_____ Unsigned
  157. | |_____ UInt128
  158. | |_____ UInt16
  159. | |_____ UInt32
  160. | |_____ UInt64
  161. | |_____ UInt8
  162. |
  163. |_____ Rational
  164. # arithmetic operators
  165. Expression Name Description
  166. +x unary plus the identity operation
  167. -x unary minus maps values to their additive inverses
  168. x + y binary plus performs addition
  169. x - y binary minus performs subtraction
  170. x * y times performs multiplication
  171. x / y divide performs division
  172. x \div y integer divide x / y, truncated to an integer
  173. x \ y inverse divide equivalent to y / x
  174. x ^ y power raises x to the yth power
  175. x % y remainder equivalent to rem(x, y)
  176. # boolean operators
  177. Expression Name
  178. !x negation
  179. x && y short-circuiting and
  180. x || y short-circuiting or
  181. # bitwise operators
  182. Expression Name
  183. ~x bitwise not
  184. x & y bitwise and
  185. x | y bitwise or
  186. xor(x, y) bitwise xor (exclusive or)
  187. nand(x, y) bitwise nand (not and)
  188. nor(x, y) bitwise nor (not or)
  189. x >>> y logical shift right
  190. x >> y arithmetic shift right
  191. x << y logical/arithmetic shift left
  192. # updating operators
  193. The updating versions of all the binary arithmetic and bitwise operators are:
  194. += -= *= /= \= \div= %= ^= &= |= >>>= >>= <<=
  195. # numeric comparisons
  196. Operator Name
  197. == equality
  198. != inequality
  199. < less than
  200. <= less than or equal to
  201. > greater than
  202. >= greater than or equal to
  203. Function Tests if
  204. isequal(x, y) x and y are identical
  205. isfinite(x) x is a finite number
  206. isinf(x) x is infinite
  207. isnan(x) x is not a number
  208. # rounding functions
  209. Function Description Return type
  210. round(x) round x to the nearest integer typeof(x)
  211. round(T, x) round x to the nearest integer T
  212. floor(x) round x towards -Inf typeof(x)
  213. floor(T, x) round x towards -Inf T
  214. ceil(x) round x towards +Inf typeof(x)
  215. ceil(T, x) round x towards +Inf T
  216. trunc(x) round x towards zero typeof(x)
  217. trunc(T, x) round x towards zero T
  218. # division functions
  219. Function Description
  220. div(x, y) truncated division; quotient rounded towards zero
  221. fld(x, y) floored division; quotient rounded towards -Inf
  222. cld(x, y) ceiling division; quotient rounded towards +Inf
  223. rem(x, y) remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x
  224. mod(x, y) modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y
  225. mod1(x, y) mod with offset 1; returns x(0, y] for y>0 or x[y,0) for y<0
  226. mod2pi(x) modulus with respect to 2pi; 0 <= mod2pi(x) < 2pi
  227. divrem(x, y) returns (div(x, y), rem(x, y))
  228. fldmod(x, y) returns (fld(x, y), mod(x, y))
  229. gcd(x, y...) greatest positive common divisor of x, y, ...
  230. lcm(x, y...) least positive common multiple of x, y, ...
  231. # sign and absolute value functions
  232. Function Description
  233. abs(x) a positive value with the magnitude of x
  234. abs2(x) the squared magnitude of x
  235. sign(x) indicates the sign of x, returning -1, 0, or +1
  236. signbit(x) indicates whether the sign bit is on (true) or off(false)
  237. copysign(x, y) a value with the magnitude of x and the sign of y
  238. flipsign(x, y) a value with the magnitude of x and the sign of x*y
  239. # powers, logs and roots
  240. Function Description
  241. sqrt(x) square root of x
  242. cbrt(x) cube root of x
  243. hypot(x, y) hypotenuse of right-angled triangle with other sides of length x and y
  244. exp(x) natural exponential function at x
  245. expm1(x) accurate exp(x)-1 for x near zero
  246. ldexp(x, n) x*2^n computed efficiently for integer values of n
  247. log(x) natural logarithm of x
  248. log(b, x) base b logarithm of x
  249. log2(x) base 2 logarithm of x
  250. log10(x) base 10 logarithm of x
  251. log1p(x) accurate log(1+x) for x near zero
  252. exponent(x) binary exponent of x
  253. significand(x) binary significand (a.k.a. mantissa) of a floating-point number x
  254. # trigonometric and hyperbolic functions
  255. sin cos tan cot sec csc
  256. sinh cosh tanh coth sech csch
  257. asin acos atan acot asec acsc
  258. asinh acosh atanh acoth asech acsch
  259. sinc cosc
  260. sinpi(x) == sin(pi*x)
  261. cospi(x) == cos(pi*x)
  262. In order to compute trigonometric functions with degrees instead of radians, suffix
  263. the function with d. For example, sind(x) computes the sine of x where x is specified
  264. in degrees. The complete list of trigonometric functions with degree variants is:
  265. sind cosd tand cotd secd cscd
  266. asind acosd atand acotd asecd acscd
  267. Reference: https://docs.julialang.org/en/v1/manual/mathematical-operations/
  268. # conversion of Integer to Float
  269. Float64(2) # 2.0 (double-precision)
  270. Float32(2) # 2.0f0 (single-precision)
  271. Float16(2) # Float16(2.0) (half-precision)
  272. # conversion of Float to Integer (the float must coincide with an integer)
  273. Int64(2.0) # 2
  274. Int64(2.4) # Error!
  275. floor(Int64, 2.4) # 2
  276. ceil(Int64, 2.4) # 3
  277. round(Int64, 2.4) # 2
  278. # math constants
  279. \pi + Tab
  280. pi
  281. \euler + Tab
  282. MathConstants.e
  283. # Integer division
  284. By default, dividing two integers could return a float. If we are interested in
  285. the integer (or Euclidean) division, the div function (or \div, unicode symbol)
  286. returns the quotient, while for the remainder we have the rem function, or %.
  287. a = 1/2 # 0.5 (Float64)
  288. div(x, y) computes x/y, truncated to an integer
  289. div(10, 3) # 3
  290. \div(10, 3) # 3
  291. fld(x, y) computes x/y, truncated to an integer
  292. fld(10, 3) # 3
  293. Note: prefer fld() than div(), since div() not work for negative integer
  294. div(-3, 2) # -1 whereas the correct answer is -2
  295. fld(-3, 2) # -2
  296. rem(x, y) computes the remainder of x/y
  297. rem(10, 3) # 1
  298. 10%3 # 1
  299. # gotcha! Integer vs Float
  300. In Julia, if you input a number like
  301. a = 2
  302. you'll be getting an Int64 by default. This can lead to errors if we are not
  303. careful. For example, consider the following operation
  304. a = 1/2^64
  305. Inf
  306. Now, that's unexpected. Two things just happened. In the first place, an Int64
  307. will overflow past 2^{64}, and the default overflow value is 0.
  308. 2^64 # returns 0
  309. In the second place, in Julia 1 divided by 0 returns Inf. We just computed 1/0.
  310. We have some alternatives:
  311. 1/2.0^64 # 5.421010862427522e-20
  312. (1/2)^64 # 5.421010862427522e-20
  313. 1.0/2^64 # Inf
  314. # file system [Reference: https://docs.julialang.org/en/v1/base/file/]
  315. > pwd()
  316. "/home/user"
  317. > cd("/home/user/Directory")
  318. > pwd()
  319. "/home/user/Directory"
  320. > cd()
  321. > pwd()
  322. "/home/user"
  323. > cd(readdir, "/home/user/Directory")
  324. "file1.sh"
  325. "file2.jl"
  326. > pwd()
  327. "/home/user"
  328. # plots in Julia - https://juliaplots.github.io/
  329. # add package with specific version number
  330. (@v1.6) pkg> add FiniteDiff@1.2
  331. # display the type of a variable
  332. typeof(variable_name)
  333. # useful commands
  334. ctrl + D # exits Julia
  335. ctrl + C # interrupts computations
  336. ? # enters help mode
  337. ; # enters system shell mode
  338. ] # enters package manager mode
  339. ctrl + l # clears screen
  340. putting ; after the expression will disable showing its value in REPL # not needed in script
  341. # essential functions in the Julia REPL (they can be also invoked in scripts)
  342. @edit max(1,2) # show the definition of max function when invoked with arguments 1 and 2
  343. varinfo() # list of global variables and their types
  344. cd("/home/user") # change working directory to /home/user/
  345. pwd() # get current working directory
  346. include("file.jl") # execute source file
  347. exit(1) # exit Julia with code 1 (exit code 0 is used by default)
  348. clipboard([1,2]) # copy data to system clipboard
  349. clipboard() # load data from system clipboard as a string
  350. # configuring PyCall to use a different python version
  351. julia> ENV["PYTHON"]="/home/saran/.envn/dsci/bin/python"
  352. "/home/saran/.envn/dsci/bin/python"
  353. julia> using Pkg
  354. julia> Pkg.bulid("PyCall")
  355. Matplotlib uses matplotlibrc configuration files to customize all kinds of properties.
  356. To display where the currently active matplotlibrc file was loaded from, one can do the
  357. following:
  358. >>> import matplotlib
  359. >>> matplotlib.matplotlib_fname()
  360. '/home/user/.config/matplotlib/matplotlibrc'
  361. Ref: PyPlot.jl - https://juliapackages.com/p/pyplot
  362. # changing font style for latex rendering using PyPlot
  363. import PyPlot
  364. const plt = PyPlot
  365. plt.rc("font", family="serif", weight="normal", size=8)
  366. plt.rc("axes", labelsize=10)
  367. https://discourse.julialang.org/t/changing-font-style-for-latex-rendering-using-PyPlot/5910
  368. # numerical methods for linear algebra
  369. Ref: https://julia.quantecon.org/tools_andtechniques/iterative_methods_sparsity.html
  370. using LinearAlgebra
  371. create 2x3 matrix: A = [2 -4 8.2; -5.5 3.5 63]
  372. size of a matrix as a pair: A_rows, A_cols = size(A)
  373. size of rows of a matrix: A_rows = size(A)[1]
  374. size of columns of a matrix: A_cols = size(A)[2]
  375. condition number of a matrix A: cond(A)
  376. inverse of a matrix A: inv(A)
  377. trace of a matrix A: tr(A)
  378. determinant of a matrix A: det(A)
  379. identity matrix: I = eye(n)
  380. zeros of a matrix: A = zeros(m, n)
  381. ones of a matrix: A = ones(m, n)
  382. transpose of a matrix: A'
  383. +/- are used for matrix addition/subtraction
  384. (matrices must have the same size): [4.0 7; -10.6 89.8] + [19 -34.7; 20 1]
  385. matrix-scalar operations (+,-,*,\) apply elementwise
  386. scalar-matrix multiplication: 10 * [1 2; 3 4] = [1 2; 3 4] * 10
  387. scalar-matrix addition: [10 10; 10 10] + [1 2; 3 4] = [1 2; 3 4] + [10 10; 10 10]
  388. matrix-vector multiplication: [1 2; 3 4] * [5, 6]
  389. matrix-matrix multiplication: [2 4 3; 3 1 5] * [3 10; 4 2; 1 7]
  390. square matrix: A*A == A^2; A*A*A == A^3; A*A*A*A == A^4
  391. sum of entries of a matrix: sum(A)
  392. average of entries of a matrix: mean(A)
  393. # pretty print an array
  394. [Ref: https://stackoverflow.com/questions/62868864/julia-how-to-pretty-print-an-array]
  395. julia> A = zeros(4,4);
  396. julia> show(stdout, A)
  397. [0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0; 0.0 0.0 0.0 0.0]
  398. julia> show(stdout, "text/plain", A)
  399. 4x4 Array{Float64,2}:
  400. 0.0 0.0 0.0 0.0
  401. 0.0 0.0 0.0 0.0
  402. 0.0 0.0 0.0 0.0
  403. 0.0 0.0 0.0 0.0
  404. # dimensions of a matrix
  405. A = zeros(4,4)
  406. size(A)
  407. # matrix operations
  408. A = [1 2 3 4; 5 6 7 8; 9 10 11 12]
  409. typeof(A) # Matrix(Int64) (alias for Array{Int64, 2})
  410. # vector equality
  411. x = [-1.1, 0.0, 3.6, -7.2]
  412. y = copy(x)
  413. y[3] = 4.0
  414. y == x # false
  415. z = x
  416. z[3] = 4.0
  417. z == x # true
  418. # printf function in julia
  419. using Printf
  420. @printf("%d \t %d \t %f\n", time, freq, result)
  421. # format program in Julia
  422. Reference: https://domluna.github.io/JuliaFormatter.jl/dev/
  423. julia> using JuliaFormatter
  424. # recursively formats all Julia files in the current directory
  425. julia> format(".")
  426. # formats an individual file
  427. julia> format_file("program.jl")
  428. # formats a string (contents of a Julia file)
  429. julia> format_text(str)
  430. # inner product
  431. x = [1 2 3]
  432. y = [3 2 1]
  433. dot(vec(x), vec(y)) == sum(x.*y)
  434. # https://www.matecdev.com/posts/julia-numerical-integration.html
  435. # functions in Julia
  436. function f(x,y)
  437. x + y
  438. end
  439. The traditional function declaration syntax demonstrated above is equivalent to
  440. the following compact "assignment form":
  441. f(x,y) = x + y
  442. # version info
  443. julia> versioninfo()
  444. julia> using CUDA
  445. julia> CUDA.versioninfo()
  446. julia> CUDA.memory_status()
  447. julia> CUDA.reclaim()
  448. Ref: https://github.com/JuliaGPU/CUDA.jl/issues/866
  449. # to execute the program inside the julia prompt
  450. julia> include("/path/to/file.jl")
  451. # profiling
  452. https://cuda.juliagpu.org/stable/development/profiling/
  453. https://morioh.com/p/0340fd968665
  454. https://thirld.com/blog/2015/05/30/julia-profiling-cheat-sheet/
  455. https://danmackinlay.name/notebook/julia_debug.html
  456. # parallel programming with Julia using MPI
  457. http://www.claudiobellei.com/2018/09/30/julia-mpi/
  458. # ODE in Julia
  459. https://nextjournal.com/sosiris-de/ode-diffeq
  460. # iteration on each index
  461. N = [10, 20]
  462. for n in eachindex(N) for m in N
  463. println(n, m)
  464. end
  465. end
  466. Output:
  467. 110
  468. 120
  469. 210
  470. 220
  471. can be written as
  472. for n in eachindex(N), m in N
  473. println(n, m)
  474. end
  475. Output:
  476. 110
  477. 120
  478. 210
  479. 220
  480. # append in Julia
  481. str = "institute"
  482. strind = collect(eachindex(str))
  483. print(strind)
  484. [1,2,3,4,5,6,7,8,9]
  485. # enumerate in julia
  486. N = 10
  487. for (m, n) in enumerate(N)
  488. println(m, n)
  489. end
  490. # symbols
  491. julia> ex = :(a+b*c)
  492. The use of the colon (:) operator in front of (a + b*c) results in the
  493. expression being saved in ex rather than being evaluated. In fact, the
  494. expression would clearly fail unless all the variables had values. The
  495. colon (:) operator creates a symbolic representation, and this is stored
  496. in a data structure Expr and is saved in ex rather than being evaluated.
  497. julia> typeof(ex); # Expr
  498. julia> a = 1.0; b = 2.5; c = 23 + 4im;
  499. julia> eval(ex)
  500. 58.5 + 10.0im
  501. # vectorized and devectorized code
  502. # vectorized code
  503. function vecadd1(a,b,c,N)
  504. for i = 1:N
  505. c = a + b
  506. end
  507. end
  508. # devectorized code
  509. function vecadd2(a,b,c,N)
  510. for i = 1:N, j = 1:length(c)
  511. c[j] = a[j] + b[j]
  512. end
  513. end
  514. julia> A = rand(2); B = rand(2); C = zeros(2);
  515. julia> @elapsed vecadd1(A,B,C,10000000)
  516. @elapsed vecadd1(A,B,C,10000000) # 18.418755286
  517. julia> @elapsed vecadd2(A,B,C,10000000)
  518. @elapsed vecadd2(A,B,C,10000000) # 0.524002398
  519. The current situation in Julia is that devectorized code is much quicker than
  520. vectorized.
  521. # get input from the user
  522. print("Enter length of side: ")
  523. s = parse(Int64, readline())
  524. a = s*s
  525. println("\nArea of square is $a")
  526. # floating-point numbers
  527. print("Enter a number: ")
  528. num = parse(Float32, readline())
  529. dnum = parse(Float64, readline())
  530. # get text/string input from the user
  531. print("Enter institute name: ")
  532. name = readline()
  533. println("Institution name is $name")
  534. # escape sequences
  535. \n newline (line feed)
  536. \$ dollar sign
  537. \\ backslash
  538. \" double quote
  539. \' single quote
  540. \r carriage return
  541. \b backspace
  542. \t horizontal tab
  543. \f form feed (new page)
  544. # reserved words
  545. baremodule begin break catch const continue do else
  546. elseif end export false finally for function global
  547. if import let local macro module quote return
  548. struct true try using while
  549. # multi-threading: starting Julia with multiple threads
  550. By default, Julia starts up with a single thread of execution. This can be
  551. verified by using the command Threads.nthreads():
  552. julia> Threads.nthreads()
  553. 1
  554. The number of execution threads is controlled either by using the -t/--threads
  555. command line argument or by using the JULIA_NUM_THREADS environment variable.
  556. The number of threads can either be specified as an integer (--threads=4) or as
  557. auto (--threads=auto), where auto sets the number of threads to the number of
  558. local CPU threads.
  559. Lets start Julia with 4 threads:
  560. $ julia --threads 4
  561. Lets verify there are 4 threads at our disposal:
  562. julia> Threads.nthreads()
  563. 4
  564. But we are currently on the master thread. To check, we use the function
  565. julia> Threads.threadid()
  566. 1
  567. # list comprehension
  568. julia> L = ['a', 'b', 'c']
  569. julia> for n in L
  570. println(n)
  571. end
  572. julia> x = [n^2 for n in 1:10]
  573. julia> println(x)
  574. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  575. julia> [(x,y) for x in [1,2] for y in [3,1] if x != y]
  576. 3-element Vector{Tuple{Int32, Int32}}:
  577. (1, 3)
  578. (2, 3)
  579. (2, 1)
  580. julia> function is_even(a)
  581. return a%2 == 0
  582. end
  583. julia> is_even(3)
  584. false
  585. julia> is_even(4)
  586. true
  587. # generators
  588. julia> x = (n^3 for n in 1:10)
  589. julia> for n in x
  590. println(n)
  591. end
  592. # functional programming tools
  593. julia> items = [1,2,3,4,5]
  594. julia> function sqr(x)
  595. return x^2
  596. end
  597. julia> map(sqr, items)
  598. 5-element Vector{Int32}:
  599. 1
  600. 4
  601. 9
  602. 16
  603. 25
  604. julia> sum(items)
  605. 15
  606. julia> minimum(items)
  607. 1
  608. julia> maximum(items)
  609. 5
  610. julia> function f(x)
  611. return x%2 != 0 && x%3 != 0
  612. end
  613. julia> filter(f, 2:25)
  614. 8-element Vector{Int32}:
  615. 5
  616. 7
  617. 11
  618. 13
  619. 17
  620. 19
  621. 23
  622. 25
  623. # diagm in julia (Ref: Statistics with Julia, Page No: 434)
  624. # information of a package
  625. julia> using SpecialFunctions
  626. julia> ?
  627. help?> SpecialFunctions
  628. # functional
  629. julia> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  630. julia> typeof(a)
  631. Vector{Int32} (alias for Array{Int32, 1})
  632. julia> reduce(+, a) # 55
  633. julia> sum(a) # 55
  634. julia> reduce(*, a) # 3628800
  635. julia> prod(a) # 3628808
  636. julia> reduce(-, a) # -53
  637. julia> reduce(/, a) # 2.7557319223985894e-7
  638. # discard the fractional part
  639. julia> x = 7.3;
  640. julia> n = trunc(x)
  641. 7.0
  642. julia> typeof(n)
  643. Float64
  644. julia> n = trunc(Int32, x)
  645. 7
  646. julia> typeof(n)
  647. Int32
  648. # alternate function declaration
  649. function f(n)
  650. n == 0 && return "zero"
  651. n == 1 && return "ones"
  652. n == 2 && return "twos"
  653. return "nothing"
  654. end
  655. julia> f(0)
  656. "zero"
  657. julia> f(1)
  658. "ones"
  659. julia> f(2)
  660. "twos"
  661. julia> f(3)
  662. "nothing'
  663. julia> f(4)
  664. "nothing"
  665. # floating-point representation of 10.375
  666. bitstring(10.375)
  667. # roots and weights of Legendre polynomials
  668. Method 1:
  669. julia> import Polynomials, SpecialPolynomials
  670. julia> p = basis(Legendre, 3) # legendre polynomial (n = 3)
  671. Legendre(1.0 P_3 (x))
  672. julia> p = convert(Polynomial, p)
  673. Polynomial(-1.5*x + 2.5*x^3)
  674. julia> node_values = roots(p)
  675. 3-element Vector{Flo
  676. -0.7745966692414834
  677. 0.7745966692414834
  678. 0.0
  679. Method 2:
  680. using FastGaussQuadrature
  681. julia> Pn = gausslegendre(3)[1] # compute roots/nodes of legendre polynomial
  682. 3-element Vector{Float64}: # to compute nodes and weights:
  683. -0.7745966692414834 # x, w = gausslegendre(3)
  684. 0.0
  685. 0.7745966692414834
  686. # finding type
  687. Reference: https://discourse.julialang.org/t/annotating-types-best-practice-for-beginners/50521/4
  688. similar(x) - creates an uninitialized array with the same type and the same dimensions as x
  689. typeof(x) - returns the type of x, can be used as a constructor
  690. eltype(x) - returns the type of elements in x
  691. # constrain two arguments to be of the same type T
  692. value = add(x::T, y::T) where T = x + y
  693. Now, add(2, 3) returns 5 and add(2, 3.0) returns ERROR: MethodError: `add`
  694. has no method matching add(::Int64, ::Float64) error message.
  695. # package compilation (Precompiling project...)
  696. julia> import Pkg;
  697. julia> Pkg.precompile()
  698. # Gnuplot
  699. julia> using Gnuplot
  700. julia> gpexec("set term sixelgd size 480,360');
  701. julia> @gp hist(randn(1000))
  702. # Gaston and Gnuplot.jl: two philosophies
  703. Gnuplot.jl is another front-end for gnuplot, with comparable capabilities to
  704. Gaston. An example serves to illustrate the differences in how the two packages
  705. approach the interface problem.
  706. Gnuplot.jl:
  707. x = 1:0.1:10
  708. @gp "set grid" "set key left" "set logscale y"
  709. @gp :- "set title 'Plot title'" "set label 'X label'" "set xrange [0:*]"
  710. @gp :- x x.^0.5 "w l tit 'Pow 0.5' dt 2 lw 2 lc rgb 'red'"
  711. @gp :- x x "w l tit 'Pow 1' dt 1 lw 3 lc rgb 'blue'"
  712. @gp :- x x.^2 "w l tit 'Pow 2' dt 3 lw 2 lc rgb 'purple'"
  713. This shows that Gnuplot.jl essentially allows one to write gnuplot commands
  714. directly in Julia. The same plot in Gaston would be:
  715. x = 1:0.1:10
  716. plot(x, x.^0.5,
  717. w = "1",
  718. legend = "'Pow 0.5'",
  719. dt = 2,
  720. lw = 2,
  721. lc = :red,
  722. Axes(grid = :on,
  723. key = "left",
  724. axis = "semilogy"))
  725. plot!(x, x,
  726. w = :l,
  727. leg = :Pow_1,
  728. dt = 1,
  729. lw = 3,
  730. lc = :blue)
  731. plot!(x, x.^2,
  732. curveconf = "w l tit 'Pow 2' dt 3 lw 2 lc 'purple'")
  733. Gaston offers a function-based interface, and gnuplot commands can be specified
  734. in a few different ways, with convenient notation, such as the optional use of
  735. "legend" instead of gnuplot's "title", symbols to avoid typing quote martks(")
  736. all the time.
  737. # help prompt (type ? in julia>)
  738. help?> PyPlot.matplotlib
  739. help?> plt.matplotlib.use
  740. julia> plt.matplotlib.rcParams
  741. julia> Pyplot.matplotlib # location of matplotlib
  742. help?> plt.rc("classic")
  743. # using classic style
  744. import PyPlot
  745. const plt = PyPlot
  746. plt.matplotlib.style.use("classic")
  747. import PyPlot.matplotlib as plt
  748. plt.style.use("classic")
  749. # factorial
  750. julia> factorial(10)
  751. julia> factorial(big(10))
  752. julia> factorial(big(100))
  753. # access the last element of an list/array
  754. x = [1, 2, 3, 4]
  755. last(x) # 4
  756. x[begin] # 1
  757. x[end] # 4
  758. julia> N = 4
  759. julia> "$N$pi"
  760. julia> "$pi/2"
  761. x1 = LinRange(-pi, pi, 10000) # prefer
  762. x2 = range(-pi, pi, 10000)
  763. julia> @time 2*x1
  764. julia> @time 2*x2
  765. julia> @time x1+x1
  766. julia> @time x2+x2
  767. julia> @timev 2*x1
  768. julia> @timev 2*x2
  769. julia> @timev x1+x1
  770. julia> @timev x2+x2
  771. x = Array{Float64}(undef, 10) # is equalent to x = zeros(10)
  772. # hit Exc and X for delete notebook cell
  773. # hit Esc and A to create notebook cell above the current cell
  774. # hit Esc and L for line numbers
  775. # Help menu for keyboard shortcuts
  776. Math Teacher's code session 1: (Shift + Enter evaluates the notebook cell)
  777. > isEven(x) = x%2 == 0
  778. > next(x) = isEven(x) ? Int(x/2) : 3x+1
  779. # division always changes to Float64 even if input is Int64
  780. > x = 7
  781. > for _ in 1:20
  782. print(x, '')
  783. x = next(x)
  784. end
  785. > while x != 1
  786. print(x, '')
  787. x = next(x)
  788. end
  789. > function colletz(x)
  790. while x != 1
  791. print(x, '')
  792. x = next(x)
  793. end
  794. print(x)
  795. end
  796. > colletz(7)
  797. > colletz(32)
  798. > collectz(27)
  799. > myArray = [2, 4, 5, 62]
  800. > function colletz(x)
  801. val = [x]
  802. while x != 1
  803. x = next(x)
  804. push!(val, x)
  805. end
  806. return val
  807. end
  808. > using PyPlot
  809. > yval = colletz(27)
  810. > n = length(yval)
  811. > xval = 1:n
  812. > plot(xval, yval)
  813. > ? push! # get info of push! function
  814. # Base.Sys
  815. > using Base.Sys
  816. > names(Sys)
  817. > cpu_info()
  818. > cpu_summary()
  819. # concatenating arrays in Julia
  820. 1. Using the 'vcat' function
  821. The vcat function in Julia allows to vertically concatenate arrays. This means that the
  822. arrays will be stacked on top of each other to create a new array.
  823. > array1 = [1, 2, 3]
  824. > array2 = [4, 5, 6]
  825. > result = vcat(array1, array2)
  826. In this example, the 'vcat' function is used to concatenate 'array1' and 'array2' into
  827. a new array called 'result'. The resulting array will be '[1, 2, 3, 4, 5, 6]'.
  828. 2. Using the 'hcat' function
  829. The hcat function in Julia allows to horizontally concatenate arrays. This means that
  830. the arrays will be placed side by side to create a new array.
  831. > array1 = [1, 2, 3]
  832. > array2 = [4, 5, 6]
  833. > result = hcat(array1, array2)
  834. In this example, the 'hcat' function is used to concatenate 'array1' and 'array2' into
  835. a new array called 'result'. The resulting array will be '[1 4; 2 5; 3 6]'.
  836. 3. Using the 'append!' function
  837. The append! function in Julia allows to append one array to another. This modifies the
  838. original array in place.
  839. > array1 = [1, 2, 3]
  840. > array2 = [4, 5, 6]
  841. > append!(array1, array2)
  842. In this example, the 'append!' function is used to append 'array2' to 'array1'. After
  843. the operation, 'array1' will be '[1, 2, 3, 4, 5, 6]'.
  844. If need to create a new array, either vertically or horizontally, then using the 'vcat'
  845. or 'hcat' functions respectively would be the way to go. However, if you want to modify
  846. an existing array in place, then using the 'append!' function would be appropriate.
  847. # writing type-stable code
  848. Code is said to be type-stable if the type of every variable does not vary over time.
  849. To clarify this idea, consider the following two closely related function definitions.
  850. function summation1(n::Int)
  851. r = 0
  852. for i in 1:n
  853. r += sin(3.4)
  854. end
  855. return r
  856. end
  857. function summation2(n::Int)
  858. r = 0.0
  859. for i in 1:n
  860. r += sin(3.4)
  861. end
  862. return r
  863. end
  864. The difference between these function definitions is that summation1 initializes
  865. r to 0, whereas summation2 initializes r to 0.0
  866. julia> summation1(100_000)
  867. -25554.110202663698
  868. julia> summation2(100_000)
  869. -25554.110202663698
  870. juliaa> @time [summation1(100_000) for i in 1:1000];
  871. 0.131536 seconds (31.90 k allocations: 2.162 MiB, 27.03% compilation time)
  872. julia> @time [summation2(100_000) for i in 1:1000];
  873. 0.129389 seconds (28.65 k allocations: 1.941 MiB, 25.74% compilation time)
  874. We can confirm that the compiler produces more complex code by examining the LLVM IR
  875. for both of these functions.
  876. julia> code_llvm(summation1, (Int, ))
  877. julia> code_llvm(summation2, (Int, ))
  878. The difference in size and complexity of code between these two functions in compiled
  879. form is considerable. And this difference is entirely attributable to the compiler's
  880. need to recheck the type of r on every iteration of the main loop in summation1, which
  881. can be optimized out in summation2, where r has a stable type.
  882. Reference:
  883. https://www.johnmyleswhite.com/notebook/2013/12/06/writing-type-stable-code-in-julia/