5

I'm translating Matlab code (written by someone else) to Python.

In one section of the Matlab code, a variable X_new is set to a value drawn from a log-normal distribution as follows:

% log normal distribution
X_new = exp(normrnd(log(X_old), sigma));

That is, a random value is drawn from a normal distribution centered at log(X_old), and X_new is set to e raised to this value.

The direct translation of this code to Python is as follows:

import numpy as np


X_new = np.exp(np.random.normal(np.log(X_old), sigma))

But numpy includes a log-normal distribution which can be sampled directly.

My question is, is the line of code that follows equivalent to the lines of code above?

X_new = np.random.lognormal(np.log(X_old), sigma)
abcd
  • 10,215
  • 15
  • 51
  • 85
  • Do you mean: is a log-normal distribution equivalent to a normal distribution where each element was used in e^x? – Chuck Mar 14 '16 at 04:48
  • @ChuckLoganLim can you rephrase that? not sure what you mean by "was used in e^x." – abcd Mar 14 '16 at 04:49
  • Err. You have normal distribution, right? You get all the y-values in that graph, use it in the expression e^y, then the resulting value for all y will form your new "distribution". – Chuck Mar 14 '16 at 04:54
  • @ChuckLoganLim you seem to be paraphrasing the following sentence from my question: "That is, a random value is drawn from a normal distribution centered at log(X_old), and X_new is set to e raised to this value." so if you're asking, is my question my question, then i guess my answer is yes. – abcd Mar 14 '16 at 04:57
  • In a way, yes. But I was generalising so as to rephrase your question in a more abstracted manner. – Chuck Mar 14 '16 at 04:59

1 Answers1

4

I think I'm going to have to answer my own question here.

From the documentation for np.random.lognormal, we have

A variable x has a log-normal distribution if log(x) is normally distributed.

Let's think about X_new from the Matlab code as a particular instance of a random variable x. The question is, is log(x) normally distributed here? Well, log(X_new) is just normrnd(log(X_old), sigma). So the answer is yes.

Now let's move to the call to np.random.lognormal in the second version of the Python code. X_new is again a particular instance of a random variable we can call x. Is log(x) normally distributed here? Yes, it must be, else numpy would not call this function lognormal. The mean of the underlying normal distribution is log(X_old) which is the same as the mean of the normal distribution in the Matlab code.

Hence, all implementations of the log-normal distribution in the question are equivalent (ignoring any very low-level implementation differences between the languages).

abcd
  • 10,215
  • 15
  • 51
  • 85