Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between random.normalvariate() and random.gauss() in python?

What is the difference between random.normalvariate() and random.gauss()?

They take the same parameters and return the same value, performing essentially the same function.

I understand from a previous answer that random.gauss() is not thread safe, but what does this mean in this context? Why should a programmer care about this? Alternatively posed, why was both a thread safe and non-thread safe version of included in Python's 'random'?

like image 775
richnis Avatar asked Jan 02 '15 22:01

richnis


People also ask

What does random Normalvariate do in Python?

normalvariate() normalvariate() is an inbuilt method of the random module. It is used to return a random floating point number with normal distribution.

How do I import a random module in Python?

import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1. Doing the import this way this requires you to use the syntax random. random() .


2 Answers

This is an interesting question. In general, the best way to know the difference between two python implementations is to inspect the code yourself:

import inspect, random str_gauss = inspect.getsource(random.gauss) str_nv=inspect.getsource(random.normalvariate) 

and then you print each of the strings to see how the sources differ. A quick look at the codes show that not only they behave differently multithread-wise, but also that the algorithms are not the same; for example, normalvariate uses something called the Kinderman and Monahan method, as per the following comments in str_nv:

# Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of random # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. 
like image 179
Lord Henry Wotton Avatar answered Sep 21 '22 09:09

Lord Henry Wotton


Thread-safe pieces of code must account for possible race conditions during execution. This introduces overhead as a result of synchronization schemes like mutexes, semaphores, etc.

However, if you are writing non-reentrant code, no race conditions normally arise, which essentially means that you can write code that executes a bit faster. I guess this is why random.gauss() was introduced, since the python doc says it's faster than the thread-safe version.

like image 30
VHarisop Avatar answered Sep 20 '22 09:09

VHarisop