Skip to content

Commit

Permalink
Merge branch 'master' of github.com:JuliaLang/julia
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Nov 30, 2014
2 parents 829e64b + 34cb0fd commit 6b0fcce
Show file tree
Hide file tree
Showing 9 changed files with 147 additions and 91 deletions.
2 changes: 2 additions & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,8 @@ export
randbool,
randn!,
randn,
randexp!,
randexp,
srand,

# bigfloat & precision
Expand Down
2 changes: 1 addition & 1 deletion base/pkg/generate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ function travis(pkg::AbstractString; force::Bool=false)
- sudo apt-get install libpcre3-dev julia -y
- if [[ -a .git/shallow ]]; then git fetch --unshallow; fi
script:
- julia --check-bounds=yes -e 'versioninfo(); Pkg.init(); Pkg.clone(pwd()); Pkg.test("$pkg")'
- julia --check-bounds=yes -e 'versioninfo(); Pkg.init(); Pkg.clone(pwd()); Pkg.build("$pkg"); Pkg.test("$pkg")'
""")
end
end
Expand Down
48 changes: 33 additions & 15 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ using Base.dSFMT
export srand,
rand, rand!,
randn, randn!,
randexp, randexp!,
randbool,
AbstractRNG, RNG, MersenneTwister,
randmtzig_exprnd
AbstractRNG, RNG, MersenneTwister


abstract AbstractRNG

Expand Down Expand Up @@ -984,23 +985,40 @@ randn(dims::Int...) = randn!(Array(Float64, dims...))
randn(rng::MersenneTwister, dims::Dims) = randn!(rng, Array(Float64, dims))
randn(rng::MersenneTwister, dims::Int...) = randn!(rng, Array(Float64, dims...))

function randmtzig_exprnd(rng::MersenneTwister=GLOBAL_RNG)
@inline function randexp(rng::MersenneTwister=GLOBAL_RNG)
@inbounds begin
while true
ri = rand_ui52(rng)
idx = ri & 0xFF
x = ri*we[idx+1]
if ri < ke[idx+1]
return x # 98.9% of the time we return here 1st try
elseif idx == 0
return ziggurat_exp_r - log(rand(rng))
elseif (fe[idx] - fe[idx+1])*rand(rng) + fe[idx+1] < exp(-x)
return x # return from the triangular area
end
end
ri = rand_ui52(rng)
idx = ri & 0xFF
x = ri*we[idx+1]
ri < ke[idx+1] && return x # 98.9% of the time we return here 1st try
return randexp_unlikely(rng, idx, x)
end
end

function randexp_unlikely(rng, idx, x)
@inbounds if idx == 0
return ziggurat_exp_r - log(rand(rng))
elseif (fe[idx] - fe[idx+1])*rand(rng) + fe[idx+1] < exp(-x)
return x # return from the triangular area
else
return randexp(rng)
end
end

function randexp!(rng::MersenneTwister, A::Array{Float64})
for i = 1:length(A)
@inbounds A[i] = randexp(rng)
end
A
end

randexp!(A::Array{Float64}) = randexp!(GLOBAL_RNG, A)
randexp(dims::Dims) = randexp!(Array(Float64, dims))
randexp(dims::Int...) = randexp!(Array(Float64, dims))
randexp(rng::MersenneTwister, dims::Dims) = randexp!(rng, Array(Float64, dims))
randexp(rng::MersenneTwister, dims::Int...) = randexp!(rng, Array(Float64, dims))


## random UUID generation

immutable UUID
Expand Down
12 changes: 8 additions & 4 deletions base/string.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1394,19 +1394,23 @@ function print_joined(io, strings, delim, last)
end
str, i = next(strings,i)
print(io, str)
while !done(strings,i)
is_done = done(strings,i)
while !is_done
str, i = next(strings,i)
print(io, done(strings,i) ? last : delim)
is_done = done(strings,i)
print(io, is_done ? last : delim)
print(io, str)
end
end

function print_joined(io, strings, delim)
i = start(strings)
while !done(strings,i)
is_done = done(strings,i)
while !is_done
str, i = next(strings,i)
is_done = done(strings,i)
print(io, str)
if !done(strings,i)
if !is_done
print(io, delim)
end
end
Expand Down
11 changes: 6 additions & 5 deletions contrib/Julia_Notepad++.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
<KeywordLists>
<Keywords name="Comments">00#</Keywords>
<Keywords name="Operators">&apos; - ! &quot; $ % &amp; * , . / : ; ? @ \ ^ ` | ~ + &lt; = &gt; &lt;: :: .+ .- .* ./ .\ .^ &amp;&amp; || // [ ] ( ) { }</Keywords>
<Keywords name="Folders in code1, open">begin do for function if immutable let quote try type while</Keywords>
<Keywords name="Folders in code1, middle">elseif else</Keywords>
<Keywords name="Folders in code1, close">end</Keywords>
<Keywords name="Delimiters">&quot;00&quot;00</Keywords>
<Keywords name="Folders in code2, open">begin do for function if immutable let quote try type while</Keywords>
<Keywords name="Folders in code2, middle">elseif else</Keywords>
<Keywords name="Folders in code2, close">end</Keywords>
<Keywords name="Delimiters">00&quot; 01\ 02&quot; 03&apos; 04\ 05&apos;</Keywords>
<Keywords name="Keywords1">abstract bitstype break ccall const continue export global import importall in local macro module baremodule return typealias using</Keywords>
<Keywords name="Keywords2">AbstractArray AbstractMatrix AbstractSparseMatrix AbstractVector Any Array ASCIIString Associative AsyncStream BitArray BigFloat BigInt BitMatrix BitVector Bool ByteString Char CharString Colon Complex Complex64 Complex128 ComplexPair DArray Dict Dims EachLine EnvHash Exception Expr FileOffset Filter Float Float32 Float64 Function ObjectIdDict Int Int8 Int16 Int32 Int64 Int128 Integer IntSet ImaginaryUnit IO IOBuffer IOStream LocalProcess Matrix NTuple Number ObjectIdDict OrdinalRange PipeBuffer ProcessGroup Ptr Range Range1 RangeIndex Ranges Rational Real Regex RegexMatch RegexMatchIterator RemoteRef RepString RevString Reverse RopeString Set Signed SparseMatrixCSC SpawnNullStream StridedArray StridedMatrix StridedVecOrMat StridedVector String SubArray SubDArray SubOrDArray SubString Symbol SymTridiagonal Task TcpSocket Tridiagonal Tuple Type UInt UInt8 UInt16 UInt32 UInt64 UInt128 Union Unsigned UTF8String UVError VecOrMat Vector VersionNumber Void WeakKeyDict WeakRef Woodbury Zip Stat Factorization BunchKaufman CholeskyDense CholeskyPivotedDense LUDense LUTridiagonal LDLTTridiagonal QRDense QRPivotedDense SVDDense GSVDDense InsertionSort QuickSort MergeSort TimSort Cchar Cuchar Cshort Cushort Cint Cuint Clong Culong Cptrdiff_t Csize_t Clonglong Culonglong Cintmax_t Cuintmax_t Cfloat Cdouble ArgumentError DisconnectException EOFError ErrorException KeyError LoadError MethodError ParseError SystemError TypeError</Keywords>
</KeywordLists>
Expand All @@ -22,8 +22,9 @@
<WordsStyle name="KEYWORDS1" fgColor="000080" bgColor="FFFFFF" fontStyle="1" fontName="Lucida Console" />
<WordsStyle name="KEYWORDS2" fgColor="FF00FF" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="OPERATORS" fgColor="008000" bgColor="FFFFFF" fontStyle="1" />
<WordsStyle name="FOLDER IN CODE1" fgColor="800000" bgColor="FFFFFF" fontStyle="0" fontName="Lucida Console" />
<WordsStyle name="FOLDER IN CODE2" fgColor="800000" bgColor="FFFFFF" fontStyle="0" fontName="Lucida Console" />
<WordsStyle name="DELIMITERS1" fgColor="800080" bgColor="FFFFFF" fontStyle="0" fontName="Lucida Console" />
<WordsStyle name="DELIMITERS2" fgColor="800080" bgColor="FFFFFF" fontStyle="0" fontName="Lucida Console" />
</Styles>
</UserLang>
</NotepadPlus>
129 changes: 63 additions & 66 deletions contrib/julia-mode.el
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@

(defvar julia-basic-offset)

(defface julia-macro-face
'((t :inherit font-lock-preprocessor-face))
"Face for Julia macro invocations."
:group 'julia-mode)

(defface julia-quoted-symbol-face
'((t :inherit font-lock-preprocessor-face))
"Face for quoted Julia symbols, e.g. :foo."
:group 'julia-mode)


;;;###autoload
(add-to-list 'auto-mode-alist '("\\.jl\\'" . julia-mode))

Expand Down Expand Up @@ -76,11 +87,13 @@ This function provides equivalent functionality, but makes no efforts to optimis
(modify-syntax-entry ?\] ")[ " table)
(modify-syntax-entry ?\( "() " table)
(modify-syntax-entry ?\) ")( " table)
;(modify-syntax-entry ?\\ "." table) ; \ is an operator outside quotes
(modify-syntax-entry ?' "." table) ; character quote or transpose
;; Here, we treat ' as punctuation (when it's used for transpose),
;; see our use of `julia-char-regex' for handling ' as a character
;; delimeter
(modify-syntax-entry ?' "." table)
(modify-syntax-entry ?\" "\"" table)
(modify-syntax-entry ?` "\"" table)
;; (modify-syntax-entry ?\" "." table)

(modify-syntax-entry ?. "." table)
(modify-syntax-entry ?? "." table)
(modify-syntax-entry ?$ "." table)
Expand All @@ -95,31 +108,28 @@ This function provides equivalent functionality, but makes no efforts to optimis
table)
"Syntax table for `julia-mode'.")

;; syntax table that holds within strings
(defvar julia-mode-string-syntax-table
(let ((table (make-syntax-table)))
table)
"Syntax table for `julia-mode'.")

;; disable " inside char quote
(defvar julia-mode-char-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?\" "." table)
table)
"Syntax table for `julia-mode'.")

(defconst julia-string-regex
"\"[^\"]*?\\(\\(\\\\\\\\\\)*\\\\\"[^\"]*?\\)*\"")

(defconst julia-char-regex
(rx (submatch (or (any "-" ";" "\\" "^" "!" "|" "?" "*" "<" "%" "," "=" ">" "+" "/" "&" "$" "~" ":")
(syntax open-parenthesis)
(syntax whitespace)
bol))
(submatch "'"
(or (repeat 0 7 (not (any "'"))) (not (any "\\"))
"\\\\")
"'")))
(rx (or (any "-" ";" "\\" "^" "!" "|" "?" "*" "<" "%" "," "=" ">" "+" "/" "&" "$" "~" ":")
(syntax open-parenthesis)
(syntax whitespace)
bol)
(group "'")
(group
(or (repeat 0 8 (not (any "'"))) (not (any "\\"))
"\\\\"))
(group "'")))

(defconst julia-triple-quoted-string-regex
;; We deliberately put a group on the first and last delimiter, so
;; we can mark these as string delimiters for font-lock.
(rx (group "\"")
(group "\"\""
;; After the delimiter, we're a sequence of
;; non-backslashes or blackslashes paired with something.
(*? (or (not (any "\\"))
(seq "\\" anything)))
"\"\"")
(group "\"")))

(defconst julia-unquote-regex
"\\(\\s(\\|\\s-\\|-\\|[,%=<>\\+*/?&|!\\^~\\\\;:]\\|^\\)\\($[a-zA-Z0-9_]+\\)")
Expand Down Expand Up @@ -191,18 +201,28 @@ This function provides equivalent functionality, but makes no efforts to optimis
"DataType" "Symbol" "Function" "Vector" "Matrix" "Union" "Type" "Any" "Complex" "None" "String" "Ptr" "Void" "Exception" "Task" "Signed" "Unsigned" "Associative" "Dict" "IO" "IOStream" "Ranges" "Rational" "Regex" "RegexMatch" "Set" "IntSet" "Expr" "WeakRef" "Nothing" "ObjectIdDict")
'symbols))

(defconst julia-quoted-symbol-regex
;; :foo and :foo2 are valid, but :123 is not.
(rx (or whitespace "(" "[" ",")
(group ":" (or letter (syntax symbol)) (0+ (or word (syntax symbol))))))

(defconst julia-font-lock-keywords
(list
;; Ensure :: and <: aren't highlighted, so we don't confuse ::Foo with :foo.
;; (in Emacs, keywords don't overlap).
(cons (rx (or "::" "<:")) ''default)
;; Highlight quoted symbols before keywords, so :function is not
;; highlighted as a keyword.
(list julia-quoted-symbol-regex 1 ''julia-quoted-symbol-face)
(cons julia-builtin-types-regex 'font-lock-type-face)
(cons julia-keyword-regex 'font-lock-keyword-face)
(cons julia-macro-regex 'font-lock-keyword-face)
(cons julia-macro-regex ''julia-macro-face)
(cons
(julia--regexp-opt
'("true" "false" "C_NULL" "Inf" "NaN" "Inf32" "NaN32" "nothing")
'symbols)
'font-lock-constant-face)
(list julia-unquote-regex 2 'font-lock-constant-face)
(list julia-char-regex 2 'font-lock-string-face)
(list julia-forloop-in-regex 1 'font-lock-keyword-face)
(list julia-function-regex 1 'font-lock-function-name-face)
(list julia-function-assignment-regex 1 'font-lock-function-name-face)
Expand All @@ -226,36 +246,11 @@ Handles both single-line and multi-line comments."
(nth 4 (syntax-ppss)))

(defun julia-in-string ()
"Return non-nil if point is inside a string."
"Return non-nil if point is inside a string.
Note this is Emacs' notion of what is highlighted as a string.
As a result, it is true inside \"foo\", `foo` and 'f'."
(nth 3 (syntax-ppss)))

(defun julia-in-char ()
"Return non-nil if point is inside a character."
(cond
((julia-in-comment) nil)
((julia-in-string) nil)
((<= (point) (1+ (point-min))) nil)
(:else
(save-excursion
;; See if point is inside a character, e.g. '|x'
;;
;; Move back past the single quote.
(backward-char 1)
;; Move back one more character, as julia-char-regex checks
;; for whitespace/paren/etc before the single quote.
(ignore-errors (backward-char 1)) ; ignore error from being at (point-min)

(if (looking-at julia-char-regex)
t
;; If point was in a \ character (i.e. we started at '\|\'),
;; we need to move back once more.
(ignore-errors
(if (looking-at (rx "'\\"))
(progn
(backward-char 1)
(looking-at julia-char-regex))
nil)))))))

(defun julia-in-brackets ()
"Return non-nil if point is inside square brackets."
(let ((start-pos (point))
Expand All @@ -266,7 +261,7 @@ Handles both single-line and multi-line comments."

(while (< (point) start-pos)
;; Don't count [ or ] inside strings, characters or comments.
(unless (or (julia-in-string) (julia-in-char) (julia-in-comment))
(unless (or (julia-in-string) (julia-in-comment))

(when (looking-at (rx "["))
(incf open-count))
Expand Down Expand Up @@ -341,7 +336,7 @@ before point. Returns nil if we're not within nested parens."
(not (plusp open-count)))

(when (looking-at (rx (any "[" "]" "(" ")")))
(unless (or (julia-in-string) (julia-in-char) (julia-in-comment))
(unless (or (julia-in-string) (julia-in-comment))
(cond ((looking-at (rx (any "[" "(")))
(incf open-count))
((looking-at (rx (any "]" ")")))
Expand Down Expand Up @@ -424,13 +419,14 @@ before point. Returns nil if we're not within nested parens."
(set (make-local-variable 'font-lock-defaults) '(julia-font-lock-keywords))
(set (make-local-variable 'font-lock-syntactic-keywords)
(list
(list "\\(\\\\\\)\\s-*\".*?\"" 1 julia-mode-char-syntax-table)))
(set (make-local-variable 'font-lock-syntactic-keywords)
(list
(list julia-char-regex 2
julia-mode-char-syntax-table)
(list julia-string-regex 0
julia-mode-string-syntax-table)
`(,julia-char-regex
(1 "\"") ; Treat ' as a string delimiter.
(2 ".") ; Don't highlight anything between the open and close '.
(3 "\"")); Treat the close ' as a string delimiter.
`(,julia-triple-quoted-string-regex
(1 "\"") ; Treat the first " in """ as a string delimiter.
(2 ".") ; Don't highlight anything between.
(3 "\"")) ; Treat the last " in """ as a string delimiter.
))
(set (make-local-variable 'indent-line-function) 'julia-indent-line)
(set (make-local-variable 'julia-basic-offset) 4)
Expand Down Expand Up @@ -2946,5 +2942,6 @@ before point. Returns nil if we're not within nested parens."

;; Local Variables:
;; coding: utf-8
;; byte-compile-warnings: (not obsolete)
;; End:
;;; julia-mode.el ends here
8 changes: 8 additions & 0 deletions doc/stdlib/base.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4119,6 +4119,14 @@ A ``MersenneTwister`` RNG can generate random numbers of the following types: ``

Fill the array A with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function.

.. function:: randexp([rng], [dims...])

Generate a random number according to the exponential distribution with scale 1. Optionally generate an array of such random numbers.

.. function:: randexp!([rng], A::Array{Float64,N})

Fill the array A with random numbers following the exponential distribution (with scale 1).

Arrays
------

Expand Down
9 changes: 9 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,20 @@ if sizeof(Int32) < sizeof(Int)

end

randn()
randn(100000)
randn!(Array(Float64, 100000))
randn(MersenneTwister(10))
randn(MersenneTwister(10), 100000)
randn!(MersenneTwister(10), Array(Float64, 100000))

randexp()
randexp(100000)
randexp!(Array(Float64, 100000))
randexp(MersenneTwister(10))
randexp(MersenneTwister(10), 100000)
randexp!(MersenneTwister(10), Array(Float64, 100000))

# Test ziggurat tables
ziggurat_table_size = 256
nmantissa = int64(2)^51 # one bit for the sign
Expand Down
Loading

0 comments on commit 6b0fcce

Please sign in to comment.