 # TODAY I LEARNED # 2 posts by enrique-meza

If you want to generate random but predictable sequences of numbers, then the rand command and the srand are not enough, you have to use a trick to save the state of the variable. Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM.

``````require 'rspec'

#i = pseudo_random 10
#p i.resume => 37
#p i.resume => 12
#p i.resume => 72
#
def pseudo_random num
srand 1

fiber = Fiber.new do
num.times do
Fiber.yield rand 100
end
end
end

describe 'Pseudo Random number generator' do
it 'creates the same sequence of random numbers' do
random_sequence = pseudo_random 3
expect(random_sequence.resume).to eq(37)
expect(random_sequence.resume).to eq(12)
expect(random_sequence.resume).to eq(72)
end
end
``````

Learned by enrique-meza on Mar 10, 2021

# Quasi-Random numbers in Ruby

I was interested in random sequence because I was in need to test the Montecarlo Method for getting Pi digits.

One method to estimate the value of π (3.141592…) is by using a Monte Carlo method. This method consists of drawing on a canvas a square with an inner circle. We then generate a large number of random points within the square and count how many fall in the enclosed circle. So, if you need a random sequence, you can use Sobol for quasi-random numbers.

``````
require 'gsl'

q = GSL::QRng.alloc(GSL::QRng::SOBOL, 2)
v = GSL::Vector.alloc(2)
for i in 0..1024 do
q.get(v)
printf("%.5f %.5f\n", v, v)
end

``````

Learned by enrique-meza on Mar 10, 2021