forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manual.tex
3254 lines (2780 loc) · 132 KB
/
manual.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass{article}
\newcommand{\thetitle}{The Julia Programming Language}
\usepackage{amsmath}
\usepackage[hyperfigures,bookmarks,bookmarksopen,bookmarksnumbered,colorlinks,linkcolor=black,citecolor=black,filecolor=blue,menucolor=black,pagecolor=blue,frenchlinks=true,pdftitle={\thetitle}]{hyperref}
\usepackage[left=1in,top=1in,right=1in,bottom=1.25in,nohead]{geometry}
\usepackage[utf8x]{inputenc}
\usepackage{tikz}
\title{\vspace{2.5in}\thetitle}
\author{
Jeff Bezanson \vspace{0.5em}\\
Stefan Karpinski \vspace{0.5em}\\
Viral Shah \vspace{0.5em}\\
Alan Edelman \vspace{0.5em}
}
\renewcommand{\sec}[1]{\label{sec:#1}}
\newcommand{\fig}[1]{\label{fig:#1}}
\newcommand{\tab}[1]{\label{tab:#1}}
\newcommand{\Section}[1]{\hyperref[sec:#1]{Section~\ref*{sec:#1}}}
\newcommand{\Figure}[1]{\hyperref[fig:#1]{Figure~\ref*{fig:#1}}}
\newcommand{\Table}[1]{\hyperref[tab:#1]{Table~\ref*{tab:#1}}}
\renewcommand{\bullet}{{$\diamond$}}
\renewcommand{\labelitemi}{\bullet}
\renewcommand{\labelitemii}{\bullet}
\renewcommand{\labelitemiii}{\bullet}
\renewcommand{\O}{\ensuremath{\operatorname{O}}}
\newcommand{\placeholder}[1]{$\left<\text{\emph{#1}}\right>$}
\begin{document}
\maketitle
\clearpage
\section*{Preface}
Scientific computing has traditionally required the highest
performance, yet domain experts have largely moved to slower dynamic
languages for daily work. We believe there are many good reasons to
prefer dynamic languages for these applications, and we do not expect
their use to diminish. Fortunately, modern language design and
compiler techniques make it possible to mostly eliminate the
performance trade-off and provide a single environment productive
enough for prototyping and efficient enough for deploying
applications. The Julia programming language fills this role: it is a
flexible, dynamic language, designed expressly for scientific
computing, and achieving performance comparable to traditional
compiled languages.
The syntax of Julia is similar to Matlab, and consequently Matlab
programmers should feel immediately comfortable with Julia. While
Matlab is quite effective for prototyping and exploring numerical
linear algebra, it has limitations for programming tasks outside of
this relatively narrow scope. Julia keeps Matlab's ease and
expressiveness for high-level numerical computing, but transcends its
general programming limitations. To achieve this, it borrows much
from the C programming language, and is strongly influenced by the
lineage of dynamic languages: Lisp, Perl, Python, Lua and Ruby.
\clearpage
\tableofcontents
\clearpage
\section{Getting Started}\sec{getting-started}
\subsection{Obtaining and Installing Julia}\sec{obtaining-and-installing}
\subsection{Running Code}\sec{running-code}
The easiest way to learn and experiment with Julia is by interacting with the read-eval-print loop (repl):
\begin{verbatim}
$ julia
_
_ _ _(_)_ |
(_) | (_) (_) |
_ _ _| |_ __ _ |
| | | | | | |/ _` | |
| | |_| | | | (_| | | 2009-2011 contributors
_/ |\__'_|_|_|\__'_| |
|__/ |
julia> 1 + 2
3
julia> ans
3
julia> load("file.j");
\end{verbatim}
When run in repl mode, \verb|julia| displays a banner and prompts the user for input.
Once the user has entered a complete expression, such as \verb|1 + 2|, and hits enter, the repl evaluates the expression and shows its value.
If an expression is entered into the repl with a trailing semicolon, its value is not shown.
The variable \verb|ans| is bound to value of the last evaluated expression whether it is shown or not.
The \verb|load| function reads and evaluates the contents of the given file.
To run code in a file non-interactively, you can give it as the first argument to the julia command:
\begin{verbatim}
$ julia script.j arg1 arg2...
\end{verbatim}
As the example implies, the following command-line arguments to julia are taken as command-line arguments to the program \verb|script.j|.
There are various ways to run Julia code and provide options, similar to those taken by the \verb|perl| and \verb|ruby| programs:
\begin{verbatim}
julia [options] [program] [args...]
-q --quiet Quiet startup without banner
-R --no-readline Disable readline functionality
-e --eval=<expr> Evaluate <expr> and don't print
-E --print=<expr> Evaluate and print <expr>
-P --post-boot=<expr> Evaluate <expr> right after boot
-H --home=<dir> Load files relative to <dir>
-T --tab=<size> Set REPL tab width to <size>
-L --lisp Start with Lisp prompt not Julia
-b --bare Bare REPL: don't load start.j
-h --help Print this message
\end{verbatim}
\section{Numbers and Arithmetic}\sec{numbers-and-arithmetic}
Julia provides a broad range of numeric types together with a full complement of arithmetic operators, bitwise operators, and common mathematical functions on them.
The following are Julia's primitive numeric types:
\begin{itemize}
\item Integer types:
\begin{itemize}
\item \verb|Int8|~: signed 8-bit integers ranging from $-2^7$ to $2^7-1$.
\item \verb|Uint8|~: unsigned 8-bit integers ranging from 0 to $2^8-1$.
\item \verb|Int16|~: signed 16-bit integers ranging from $-2^{15}$ to $2^{15}-1$.
\item \verb|Uint16|~: unsigned 16-bit integers ranging from 0 to $2^{16}-1$.
\item \verb|Int32|~: signed 32-bit integers ranging from $-2^{31}$ to $2^{31}-1$.
\item \verb|Uint32|~: unsigned 32-bit integers ranging from 0 to $2^{32}-1$.
\item \verb|Int64|~: signed 64-bit integers ranging from $-2^{63}$ to $2^{63}-1$.
\item \verb|Uint64|~: unsigned 64-bit integers ranging from 0 to $2^{64}-1$.
\end{itemize}
\item Floating point types:
\begin{itemize}
\item \verb|Float32|~: IEEE 754 32-bit floating point numbers.
\item \verb|Float64|~: IEEE 754 64-bit floating point numbers.
\end{itemize}
\end{itemize}
Full support for complex and rational numbers is built on top of these primitive numeric types.
All numeric types interoperate naturally without explicit casting, thanks to a flexible type promotion system.
Moreover, this promotion system (detailed in \Section{conversion-and-promotion}) is user-extensible, so user-defined numeric types can be made to interoperate just as naturally with built in numerics and with each other.
\subsection{Integer Literals}\sec{integer-literals}
The default type for an integer literal is \verb|Int32|:
\begin{verbatim}
julia> typeof(1)
Int32
\end{verbatim}
Larger integer literals which cannot be represented using only 32 bits but can be represented in 64 bits create 64-bit integers:
\begin{verbatim}
julia> typeof(4294967296)
Int64
\end{verbatim}
Integers can be input in hexadecimal form using the \verb|0x| prefix as in C:
\begin{verbatim}
julia> 0xff
255
julia> typeof(ans)
Int32
julia> 0xffffffff
4294967295
julia> typeof(ans)
Int64
\end{verbatim}
There is no literal input format for integer types besides \verb|Int32| and \verb|Int64|. You can, however convert \verb|Int32| and \verb|Int64| values to other types easily:
\begin{verbatim}
julia> int8(-15)
-15
julia> typeof(ans)
Int8
julia> uint8(231)
231
julia> typeof(ans)
Uint8
\end{verbatim}
\subsection{Floating Point Literals}\sec{floating-point-literals}
Floating point numbers are input in the standard formats:
\begin{verbatim}
julia> 1.0
1.0
julia> 1.
1.0
julia> 0.5
0.5
julia> .5
0.5
julia> -1.23
-1.23
julia> 1e10
1e+10
julia> 2.5e-4
0.00025
\end{verbatim}
The above results are all \verb|Float64| values. There is no literal format for \verb|Float32|, but you can convert values to \verb|Float32| easily:
\begin{verbatim}
julia> float32(-1.5)
-1.5
julia> typeof(ans)
Float32
\end{verbatim}
There are three specified standard floating point values that do not correspond to a point on the real number line: infinity (\verb|Inf|), minus infinity (\verb|-Inf|), and not-a-number (\verb|NaN|).
By the IEEE 754 standard, these floating point values are the results of certain arithmetic operations:
\begin{verbatim}
julia> 1/0
Inf
julia> -5/0
-Inf
julia> 0.000001/0
Inf
julia> 0/0
NaN
julia> 500 + Inf
Inf
julia> 500 - Inf
-Inf
julia> Inf - Inf
NaN
julia> Inf/Inf
NaN
\end{verbatim}
\subsection{Arithmetic Operators}\sec{arithmetic-operators}
The following arithmetic and bitwise operators are supported on numeric types:
\begin{itemize}
\item Arithmetic operators (all numeric types):
\begin{itemize}
\item \verb|+x|~: unary plus is the identity operation.
\item \verb|-x|~: unary minus maps values to their additive inverses.
\item \verb|x + y|~: binary plus performs addition.
\item \verb|x - y|~: binary minus performs subtraction.
\item \verb|x * y|~: times performs multiplication.
\item \verb|x / y|~: divide performs division.
\end{itemize}
\item Bitwise operators (integer types only)\,:
\begin{itemize}
\item \verb|~x|~: bitwise not.
\item \verb|x & y|~: bitwise and.
\item \texttt{x | y}~: bitwise or.
\item \verb|x $ y|~: bitwise xor.
\item \verb|x << y|~: logical shift left.
\item \verb|x >> y|~: logical shift right.
\item \verb|x >>> y|~: arithmetic shift right.
\end{itemize}
\end{itemize}
Here are some simple examples using arithmetic operators:\,\footnote{By convention, we tend to space less tightly binding operators less tightly, but there are no syntactic constraints.}
\begin{verbatim}
julia> 1 + 2 + 3
6
julia> 1 - 2
-1
julia> 3*2/12
0.5
\end{verbatim}
Julia has a type promotion system that allows arithmetic operations on mixtures of argument types to ``just work'' naturally and automatically (see \Section{conversion-and-promotion} for details of the promotion system):
\begin{verbatim}
julia> 1 + 2.5
3.5
julia> 0.5*12
6.0
julia> 3*2/12 + 1
1.5
\end{verbatim}
The above expressions all promote to \verb|Float64| since that is the smallest floating point type that can faithfully represent all possible \verb|Int32| values.
However, more nuanced promotions also work:
\begin{verbatim}
julia> uint8(12) - int8(15)
-3
julia> typeof(ans)
Int16
julia> uint8(12) - float32(1.5)
10.5
julia> typeof(ans)
Float32
\end{verbatim}
Here are some examples with bitwise operators:
\begin{verbatim}
julia> ~123
-124
julia> ~uint32(123)
4294967172
julia> ~uint8(123)
132
julia> 123 & 234
106
julia> 123 | 234
251
julia> typeof(ans)
Int32
julia> uint8(123) | uint16(234)
251
julia> typeof(ans)
Uint16
julia> 123 $ 234
145
\end{verbatim}
As a general rule of thumb, arguments are promoted to the smallest type that can accurately represent all of the arguments.
Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand.
For example, the updating form of \verb|+| is the \verb|+=| operator.
Writing \verb|x += 3| is equivalent to writing \verb|x = x + 3|:
\begin{verbatim}
julia> x = 1
1
julia> x += 3
4
julia> x
4
\end{verbatim}
The updating versions of arithmetic and bitwise operators are:
\verb|+= -= *= /= &=|\hspace{1.3ex}\texttt{|=}\hspace{1.3ex}\verb|$= <<= >>= >>>=|\,.
\subsection{Numeric Comparisons}\sec{numeric-comparisons}
Standard comparison operations are defined for primitive numeric types:
\begin{itemize}
\item \verb|==|~: equality.
\item \verb|!=|~: inequality.
\item \verb|<|~: less than.
\item \verb|<=|~: less than or equal to.
\item \verb|>|~: greater than.
\item \verb|>=|~: greater than or equal to.
\end{itemize}
Here are some simple examples:
\begin{verbatim}
julia> 1 == 1
true
julia> 1 == 2
false
julia> 1 != 2
true
julia> 1 == 1.0
true
julia> 1 < 2
true
julia> 1.0 > 3
false
julia> 1 >= 1.0
true
julia> -1 <= 1
true
julia> -1 <= -1
true
julia> -1 <= -2
false
julia> 3 < -0.5
false
\end{verbatim}
As is evident here, promotion also applies to comparisons:
the comparisons are performed in whatever type the arguments are promoted to, which is generally the smallest type in which all the values can be faithfully represented.
After promotion to a common type, integers are compared in the standard manner:
by comparison of bits.
Floating point numbers are compared according to the IEEE 754 standard:
finite numbers are ordered in the usual manner;
infinity is equal to itself and greater than everything else except \verb|NaN|;
minus infinity is equal to itself and less then everything else except \verb|NaN|;
and \verb|NaN| is not equal to, less than, or greater than anything, including itself:
\begin{verbatim}
julia> NaN == NaN
false
julia> NaN != NaN
true
julia> NaN < NaN
false
julia> NaN > NaN
false
\end{verbatim}
For situations where one wants to compare floating point values so that \verb|NaN| equals \verb|NaN|, such as hash key comparisons, the function \verb|isequal| is also provided, which considers \verb|NaN|s to be equal to each other:
\begin{verbatim}
julia> isequal(NaN,NaN)
true
\end{verbatim}
Unlike most languages, comparisons can be arbitrarily chained:
\begin{verbatim}
julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
true
\end{verbatim}
Chaining comparisons is often quite convenient in numerical code.
Only as many initial comparisons and their operand expressions as are necessary to determine the final truth value of the entire chain are evaluated.
See \Section{short-circuit-evaluation} for further discussion of this behavior.
\subsection{Mathematical Functions}
Julia provides a comprehensive set of mathematical functions and operators.
These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions.
The following is a partial list of functions and operators provided:
\begin{itemize}
\item \verb|div(x,y)| --- truncated division; quotient rounded towards zero.
\item \verb|fld(x,y)| --- floored division; quotient rounded towards $-\infty$.
\item \verb|rem(x,y)| --- remainder; satisfies \verb|x == div(x,y)*y + rem(x,y)|, implying that sign matches \verb|x|.
\item \verb|mod(x,y)| --- modulus; satisfies \verb|x == fld(x,y)*y + mod(x,y)|, implying that sign matches \verb|y|.
\item \verb|x % y| --- equivalent to \verb|mod(x,y)|.
\item \verb|gcd(x,y...)| --- greatest common divisor of \verb|x|, \verb|y|... with sign matching \verb|x|.
\item \verb|lcm(x,y...)| --- least common multiple of \verb|x|, \verb|y|... with sign matching \verb|x|.
\item \verb|sign(x)| --- indicates the sign of \verb|x| using $-1$, $0$, $+1$.
\item \verb|signbit(x)| --- indicates the sign bit of \verb|x| using $-1$, $+1$.\footnote{For IEEE floating point values, this has precise specified semantics.
In particular, there are both positive and negative zero and \texttt{NaN} values.
For other numeric types, this is essentially just a test of whether \texttt{x < 0} or not.}
\item \verb|copysign(x,y)| --- a value with the magnitude of \verb|x| and the sign of \verb|y|.
\item \verb|sqrt(x)| --- the square root of \verb|x|.
\item \verb|exp(x)| --- the natural exponential function $e^x$ at \verb|x|.
\item \verb|x^y| --- \verb|x| raised to the exponent \verb|y| ($x^y$).
\item \verb|log(x)| --- the natural logarithm of \verb|x|.
\item \verb|log2(x)| --- the base 2 logarithm of \verb|x|.
\item \verb|log10(x)| --- the base 10 logarithm of \verb|x|.
\item \verb|log(b,x)| --- the base \verb|b| logarithm of \verb|x|.
\end{itemize}
Additionally, all the standard trigonometric functions are defined:
\verb|sin|, \verb|cos|, \verb|tan|, \verb|cot|, \verb|sec|, \verb|csc|,
\verb|sinh|, \verb|cosh|, \verb|tanh|, \verb|coth|, \verb|sech|, \verb|csch|,
\verb|asin|, \verb|acos|, \verb|atan|, \verb|acot|, \verb|asec|, \verb|acsc|,
\verb|acoth|, \verb|asech|, \verb|acsch|, \verb|sinc|, \verb|cosc|.
The mathematical functions with operator notation, \verb|%| and \verb|^|, both also have an updating form, like the arithmetic and bitwise operators:
\begin{verbatim}
julia> x = 2; x ^= 5; x
32
julia> x = 7; x %= 4; x
3
\end{verbatim}
Like the updating forms of other operators, \verb|x ^= y| means \verb|x = x^y| and \verb|x %= y| means \verb|x = x % y|.
\subsection{Numeric Literal Coefficients}
To make common numeric formulas and expressions clearer, Julia allows variables to be immediately preceded by a numeric literal, implying multiplication.
This makes writing polynomial expressions much cleaner:
\begin{verbatim}
julia> x = 3
3
julia> 2x^2 - 3x + 1
10
julia> 1.5x^2 - .5x + 1
13.0
\end{verbatim}
% TODO: note about variables and assignment.
You can also use a numeric literal coefficients with parenthesized expressions:
\begin{verbatim}
julia> 2(x-1)^2 - 3(x-1) + 1
3
\end{verbatim}
These two simple syntactic enhancements significantly reduce the visual noise incurred when writing common mathematical formulae.
Note that no space may come between a numeric literal coefficient and the identifier or parenthesized expression which it multiplies.
Juxtaposed coefficients conflict with two numeric literal syntaxes:
hexadecimal integer literals and engineering notation for floating point literals.
Here are some situations where syntactic conflicts arise:
\begin{itemize}
\item The hexadecimal integer literal expression \verb|0xff| could be interpreted as the numeric literal \verb|0| multiplied by the variable \verb|xff|.
\item The floating point literal expression \verb|1e10| could be interpreted as the numeric literal \verb|1| multiplied by the variable \verb|e10|, and similarly with the equivalent \verb|E| form.
\end{itemize}
In both cases, we resolve the ambiguity in favor of interpretation as a numeric literals:
\begin{itemize}
\item Expressions starting with \verb|0x| are always hexadecimal literals.
\item Expressions starting with $d.dd$\,\verb|e| or $d.dd$\,\verb|E| are always floating point literals.
\end{itemize}
One final note is that parenthesized expressions can also be used as coefficients to variables:
\begin{verbatim}
julia> (x-1)x
6
\end{verbatim}
Juxtaposing two parenthesized expressions, however, does not imply multiplication:
\begin{verbatim}
julia> (x-1)(x+1)
type error: apply: expected Function, got Int32
\end{verbatim}
The error occurs since parentheses following an expression which is not a numeric literal introduces a function call, not multiplication, and the value of \verb|(x-1)| is an integer rather than a function.
\subsection{Complex Numbers}
The global constant \verb|im| is bound to the complex number $i$, representing one of the square roots of $-1$.
Since Julia allows numeric literals to be juxtaposed with identifiers as coefficients, this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation, $1 + 2i$:\,\footnote{It was deemed harmful to co-opt the name \texttt{i} for a global constant, as that would preclude its use as a variable.}
\begin{verbatim}
julia> 1 + 2im
1 + 2im
\end{verbatim}
You can perform all the standard arithmetic operations with complex numbers:
\begin{verbatim}
julia> (1 + 2im)*(2 - 3im)
8 + 1im
julia> (1 + 2im)/(1 - 2im)
-0.6 + 0.8im
julia> (1 + 2im) + (1 - 2im)
2 + 0im
julia> (-3 + 2im) - (5 - 1im)
-8 + 3im
julia> (-1 + 2im)^2
-3 - 4im
julia> (-1 + 2im)^2.5
2.7296244647840089 - 6.9606644595719001im
julia> (-1 + 2im)^(1 + 1im)
-0.2791038107582666 + 0.0870805341410243im
julia> 3(2 - 5im)
6 - 15im
julia> 3(2 - 5im)^2
-63 - 60im
julia> 3(2 - 5im)^-1
0.2068965517241379 + 0.5172413793103448im
\end{verbatim}
The promotion mechanism ensures that combinations of operands of different types just work:
\begin{verbatim}
julia> 2(1 - 1im)
2 - 2im
julia> (2 + 3im) - 1
1 + 3im
julia> (1 + 2im) + 0.5
1.0 + 2.5im
julia> (2 + 3im) - 0.5im
2.0 + 2.5im
julia> 0.75(1 + 2im)
0.75 + 1.5im
julia> (2 + 3im) / 2
1.0 + 1.5im
julia> (1 - 3im) / (2 + 2im)
-0.5 - 1.0im
julia> 1 + 3/4im
1.0 + 0.75im
\end{verbatim}
Note that \verb|3/4im| parses as \verb|3/4*im|, which, since division and multiplication have equal precedence, is equivalent to \verb|(3/4)*im| rather than the quite different value, \verb|3/(4im) == -(3/4)im|.
Standard functions to manipulate complex values are provided:
\begin{verbatim}
julia> real(1 + 2.5im)
1.0
julia> imag(1 + 2.5im)
2.5
julia> conj(1 + 2.5im)
1.0 - 2.5im
julia> norm(1 + 2.5im)
7.25
julia> abs(1 + 2.5im)
2.6925824035672519
\end{verbatim}
The full gamut of mathematical functions are also defined for complex numbers:
\begin{verbatim}
julia> sqrt(im)
0.7071067811865476 + 0.7071067811865475im
julia> sqrt(1 + 2im)
1.272019649514069 + 0.7861513777574233im
julia> cos(1 + 2im)
2.0327230070196656 - 3.0518977991517997im
julia> exp(1 + 2im)
-1.1312043837568135 + 2.4717266720048188im
julia> sinh(1 + 2im)
-0.4890562590412937 + 1.4031192506220405im
\end{verbatim}
If you need to construct a complex number using variables, the literal numeric coefficient notation will not work, so you have to explicitly write the multiplication operation:
\begin{verbatim}
julia> a = 1; b = 2; a + b*im
1 + 2im
\end{verbatim}
\subsection{Rational Numbers}
Julia has rational numbers to represent exact ratios of integers.
Rationals are constructed by the \texttt{//} operator:
\begin{verbatim}
julia> 2//3
2//3
\end{verbatim}
If the numerator and denominator of a rational have common factors, they are reduced to lowest terms such that the denominator is non-negative:
\begin{verbatim}
julia> 6//9
2//3
julia> -4//8
-1//2
julia> 5//-15
-1//3
julia> -4//-12
1//3
\end{verbatim}
This normalized form for a ratio of integers is unique, so equality of rational values can be tested by checking for equality of the numerator and denominator.
The standardized numerator and denominator of a rational value can be extracted using the \verb|num| and \verb|den| functions:
\begin{verbatim}
julia> num(2//3)
2
julia> den(2//3)
3
\end{verbatim}
Direct comparison of the numerator and denominator is generally not necessary, since the standard arithmetic and comparison operations are defined for rational values:
\begin{verbatim}
julia> 2//3 == 6//9
true
julia> 2//3 == 9//27
false
julia> 3//7 < 1//2
true
julia> 3//4 > 2//3
true
julia> 2//4 + 1//6
2//3
julia> 5//12 - 1//4
1//6
julia> 5//8 * 3//12
5//32
julia> 6//5 / 10//7
21//25
\end{verbatim}
Rationals can be easily converted to floating point numbers:
\begin{verbatim}
julia> float(3//4)
0.75
\end{verbatim}
Conversion from rational to floating point respects the following identity for any integral values of \verb|a| and \verb|b|:
\begin{verbatim}
julia> isequal(float(a//b), a/b)
true
\end{verbatim}
This includes cases where \verb|a == 0| or \verb|b == 0|, in which situations the conversion from rational value to floating point produces the appropriate $\pm$\verb|Inf| or \verb|NaN| value:
\begin{verbatim}
julia> 5//0
1//0
julia> float(ans)
Inf
julia> 0//0
0//0
julia> float(ans)
NaN
julia> -3//0
-1//0
julia> float(ans)
-Inf
\end{verbatim}
In a sense, Julia's rational values are a convenient way of deferring the computation of integer ratios, thereby allowing exact canceling of common factors and avoiding accumulation of floating point errors.
As usual, the promotion system makes interactions with other numeric types natural and effortless:
\begin{verbatim}
julia> 3//5 + 1
8//5
julia> 3//5 - 0.5
0.1
julia> 2//7 * (1 + 2im)
2//7 + 4//7im
julia> 2//7 * (1.5 + 2im)
0.4285714285714285 + 0.5714285714285714im
julia> 3//2 / (1 + 2im)
3//10 - 3//5im
julia> 1//2 + 2im
1//2 + 2//1im
julia> 1 + 2//3im
1//1 + 2//3im
julia> 0.5 == 1//2
true
julia> 0.33 == 1//3
false
julia> 0.33 < 1//3
true
julia> 1//3 - 0.33
0.0033333333333333
\end{verbatim}
\section{Strings}
\sec{strings}
% Traditionally, strings are conceptualized as sequences of characters, which mathematically is a function from indices to characters.
% When all characters are exactly one byte, this can be conveniently and efficiently represented with a plain old array of bytes.
% It's simple and efficient.
% End of story.
%
% Unicode complicates things because common encodings like UTF-8 and UTF-16 are variable-width, meaning that characters require different numbers of bytes in their representation.
% In UTF-8, for example, all of the ASCII characters are one byte, encoded just as in ASCII.
% All other characters, however, take between two and four bytes to represent.
% This means that you can't efficiently look up the $k$th character of a string by doing array indexing anymore:
% the $k$th byte of the representation is no longer the $k$th character.
% Worse still, a byte might not be the beginning of a character at all, but right in the middle of a character (this is called a ``continuation byte'').
%
% If you allow people direct access to the bytes of an encoded string, they can and will do all sorts of bad things that produce invalid Unicode and broken behaviors when Unicode input is received.
% To provide a string abstraction that makes strings behave like functions from indices to Unicode characters (i.e. code points), you have to chose one of the following:
% \begin{enumerate}
%
% \item Have fast, natural random access to characters, but store strings so that every character is big enough to accommodate the entire Unicode character set.
% The natural choice of encoding for this is UTF-32, in which each code point (integer value representing a unique character) is simply represented by its 32-bit integer value.
% This also requires processing every string before accessing or manipulating it to convert it from its input encoding (usually UTF-8) to UTF-32.
% Transcoding introduces a lot of overhead, forcing every string to be transcoded, typically both on input and output, as well as inflating memory usage for all strings.
%
% \item Sacrifice the ability to represent every Unicode character and use only the two-byte characters of a 16-bit encoding like UTF-16.
% With this you can represent virtually all modern languages, but you cannot write in ancient languages like Egyptian hieroglyphs, Linear B, or represent some unusual modern characters such as certain unified Han ideographs.
% This allows fast random access, and reduces the memory inflation compared to the UTF-32 approach, but still requires transcoding almost every string on input and output.
%
% \item Keep strings in their input form, but make indexing into a string an $\O(k)$ operation which requires scanning the entire string from the beginning to find the $k$th character from there.
% This turns a lot of straightforward $\O(n)$ string processing algorithms into $\O(n^2)$ algorithms unless you completely avoid indexing into strings altogether.
%
% \item Represent strings by a clever, relatively complex data structure that allows strings to remain encoded, but somehow makes indexing the $k$th character look like it's faster than $\O(k)$, when it is amortized over many operations.
% One possible way to do this is to remember the last few indices that were accessed and figure out new indices relative to them.
%
% \item Do not allow indexing into strings. Instead, only provide interfaces, such as iterating characters, which are Unicode safe as well as being efficiently implementable without transcoding strings.
%
% \item Ignore the whole issue and just equate strings with byte arrays and let Unicode bugger itself (a.k.a.~the C approach\footnote{To be fair, the C language long predates the Unicode standard.}).
%
% \end{enumerate}
% Technically, option 5 doesn't actually keep the abstraction of strings as functions from indices to characters, so perhaps it doesn't belong here;
% and option 6 isn't a solution at all, but rather a matter of deciding that you just don't care.
% Option 2 is not really a solution, either, but a pragmatic compromise that gets you 90\% of the way (unless you happen to want to process hieroglyphs).
% Frankly, none of these options is good enough for something as fundamental and performance-critical as string processing.
%
% \subsection{The Partial Function Approach}
% \sec{partial-function-strings}
%
% Our approach is to change the abstraction of what a string is instead of choosing any of the above.
% Rather than conceptualizing a string as a function from indices to characters, we conceptualize a string as a \emph{partial function} from indices to characters.
% What does this mean?
% It means that when indexing into a string, for some indices no character value is returned:
% instead of returning a value, the language throws an exception.
% So in short \verb|str[k]| will throw an exception if $k$ doesn't correspond to a character.
% For UTF-8 strings that are plain ASCII this will never happen.
% For UTF-32 strings it will never happen.
% For UTF-16 strings including only the common two-byte characters it will never happen.
% For other instances of encoded strings, it could happen, however.
%
% How does this modified abstraction help?
% It recognizes that bytes and characters are not one-to-one in many encodings, but still allows you store strings in their native encoding and retrieve characters efficiently by a byte index, rather than a character index.
% If you try to get or set a character at an index that isn't the start of a character, it's an exception---indicating that the partial function isn't defined there.
% The ``string''---as one normally thinks of it---is the sequence characters returned by the string as the indices range from one to the maximum index.
% The gotcha is that some indices don't return a character.
%
% Code that na\"ively iterates through all indices will work and work with C-like performance, until it encounters strange input data, at which point it will throw a nice clean exception letting you know exactly what the problem is.
% You can probably just modify the code to catch the exception and move on to the next index.
% Alternately, you can rewrite the code to use a Unicode character iterator instead.
% Moreover, if you always consider string indices as opaque objects, and never do arithmetic with them (iterating through indices counts as arithmetic: \verb|k+=1|), then as long as you only index into a string with an index given to you by a string function, this kind of thing will never happen.
%
% By changing the string abstraction, we can support arbitrary string encodings and other representations at C-like efficiency and with a nice, safe, clean programmatic interface.
There are a few noteworthy high-level features about Julia's approach to strings:
\begin{itemize}
\item Like C, but unlike most dynamic languages, Julia has a first-class type representing a single character, called \verb|Char|.
A \verb|Char| is a special kind of 32-bit integer, whose numeric value represents a single Unicode code point.
\item Conceptually, a \verb|String| is a \emph{partial function} from indices to \verb|Char| values --- for some index values, no character value is returned, and instead an exception is thrown.
This for allows efficient indexing into strings by the byte index of an encoded representation rather than by a character index, which cannot be implemented efficiently and simply for variable-width encodings of Unicode strings.
\item There are many different classes implementing the \verb|String| interface, not a single special one.
They all implement a common programming interface, however, and any string type can be used in any function expecting a \verb|String|.
The predefined string types are no more special than user-defined ones.
\item Strings are immutable: the value of a \verb|String| object cannot be changed.
To construct a different string value, you construct a new string object from parts of other string objects.
\end{itemize}
Although there are various implementations of the \verb|String| interface, we do not delve into the details of these variations here:
you can use all strings transparently in the same way in all string operations.
\subsection{Characters}
Like C, but unlike Perl, Python, or Ruby, Julia has a type for individual characters: \verb|Char|.
A \verb|Char| is just a 32-bit integer with a special literal representation and some specific arithmetic behaviors, interpreted as a Unicode code point.
Here is how \verb|Char| values are input and shown:
\begin{verbatim}
julia> 'x'
'x'
julia> typeof(ans)
Char
\end{verbatim}
You can convert a \verb|Char| to its integer value, i.e. code point, easily:
\begin{verbatim}
julia> int('x')
120
julia> typeof(ans)
Int32
\end{verbatim}
You can convert an integer value back to a \verb|Char| just as easily:
\begin{verbatim}
julia> char(120)
'x'
\end{verbatim}
Not all integer values are valid Unicode code points, but for performance, the \verb|char| conversion does not check that every character value is valid.
If you want to check that each converted value is a value code point, use the \verb|safe_char| conversion instead:
\begin{verbatim}
julia> char(0xd800)
'???'
julia> safe_char(0xd800)
invalid Unicode code point: U+d800
julia> char(0x110000)
'\U00110000'
julia> safe_char(0x110000)
invalid Unicode code point: U+110000
\end{verbatim}
As of this writing, the valid Unicode code points are \verb|U+0000| through \verb|U+d7ff| and \verb|U+e000| through \verb|U+10ffff|.
These have not all been assigned intelligible meanings yet, nor are they necessarily interpretable by applications, but all of these values are considered to be valid Unicode characters.
You can input any Unicode character in single quotes using \verb|\u| followed by up to four hexadecimal digits or \verb|\U| followed by up to eight hexadecimal digits (the longest valid value only requires six):
\begin{verbatim}
julia> '\u0'
'\0'
julia> '\u78'
'x'
julia> '\u2200'
'∀'
julia> '\U10ffff'
'\U0010ffff'
\end{verbatim}
Julia uses your system's locale and language settings to determine which characters can be printed as-is and which must be output using the generic, escaped \verb|\u| or \verb|\U| input forms.
In addition to these Unicode escape forms, all of C's traditional escaped input forms are usable as well:
\begin{verbatim}
julia> int('\0')
0
julia> int('\t')
9
julia> int('\n')
10
julia> int('\e')
27
julia> int('\x7f')
127
julia> int('\177')
127
julia> int('\xff')
255
\end{verbatim}
Like any integers, you can do arithmetic and comparisons with \verb|Char| values:
\begin{verbatim}
julia> 'x' - 'a'
23
julia> 'A' < 'a'
true
julia> 'A' <= 'a' <= 'Z'
false
julia> 'A' <= 'X' <= 'Z'
true
\end{verbatim}
Arithmetic with \verb|Char| values always promotes them to \verb|Int32|.
To create a new \verb|Char| value, explicit conversion back to the \verb|Char| type is required:
\begin{verbatim}
julia> 'A' + 1
66
julia> char(ans)
'B'
\end{verbatim}
% Requiring explicit conversion allows a series of intermediate computations to be done efficiently, only checking that the final value is a valid Unicode code point.
\subsection{String Basics}
Here a variable is initialized with a simple string literal:
\begin{verbatim}
julia> str = "Hello, world.\n"
"Hello, world.\n"
\end{verbatim}
If you want to extract a character from a string, you index into it:
\begin{verbatim}
julia> str[1]
'H'
julia> str[6]
','
julia> str[end]
'\n'
\end{verbatim}
All indexing in Julia is 1-based like Matlab and Mathematica, rather than 0-based like most other programming languages:
the first element of any integer-indexed object is found at index \verb|1|, not index \verb|0|, and the last element is found at index \verb|n| rather than \verb|n-1|, when the object has a length of \verb|n|.
In any indexing expression, the keyword, \verb|end|, can be used as a shorthand for \verb|length(x)|, where \verb|x| is the object being indexed into, whether it is a string, an array, or some other indexable object.
You can perform arithmetic and other operations with \verb|end|, just like a normal value:
\begin{verbatim}
julia> str[end-1]
'.'
julia> str[end/2]
' '
julia> str[end*1/3]
'o'
julia> str[end*2/3]
'o'
\end{verbatim}
Using an index less than 1 or greater than \verb|end| raises an error:
\begin{verbatim}
julia> str[0]
in next: arrayref: index out of range