Shixiang Wang
Shixiang Wang

Reputation: 2391

Julia cannot reproduce the rand

I am just reading and practicing the "3.5.2.1 rand" section of https://juliadatascience.io/standardlibrary and found the code below cannot reproduce same random numbers:

$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.7.0 (2021-11-30)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> using Random: rand, randn, seed!

julia> my_seed = seed!(123)
Random.TaskLocalRNG()

julia> rand(my_seed, 3)

3-element Vector{Float64}:
 0.521213795535383
 0.5868067574533484
 0.8908786980927811

julia> rand(my_seed, 3)
3-element Vector{Float64}:
 0.19090669902576285
 0.5256623915420473
 0.3905882754313441

The snapshot of the book:

enter image description here

Upvotes: 2

Views: 214

Answers (2)

RikH
RikH

Reputation: 3424

Well spotted. Running rand(my_seed, 3) twice shouldn't give the same output. This problem was caused by a bug in Books.jl. The Books package stores outputs in files as a sort of caching mechanism. Unfortunately, two identical blocks of code will be written to the same file path, so the output for the last block overrides the output for the first block. I still haven't found a nice solution to that problem and normally it isn't a problem because the same code will usually give the same output, but not for calling rand.

This problem will be fixed in the HTML and PDF version on the website about 30 minutes after https://github.com/JuliaDataScience/JuliaDataScience/pull/235 is merged.

Upvotes: 2

Oscar Smith
Oscar Smith

Reputation: 6398

You're missing the second call to seed! that's in the book.

Upvotes: 2

Related Questions