-1

I have to perform a Monte-Carlo scan over the parameters suppose x, y, z in the range x->(4, 8), y->(-5, 7), z->(1,9) and for 4000 random parameter points in these given ranges, I have to determine value of some functions defined by x, y, z. So, how to do the MC scan for such a problem in python and directly input those different datasets to my program ?

user105697
  • 39
  • 2
  • 9

1 Answers1

1

Since Monte Carlo is just throwing numbers at the function and seeing what sticks, this is just something like this in vanilla Python.

import random

def fun(x, y, z):
    return (x * y) + z

trials = []

for i in range(4000):
    x = random.uniform(4, 8)
    y = random.uniform(-5, 7)
    z = random.uniform(1, 9)
    value = fun(x, y, z)
    trials.append(((x, y, z), value))

If you want, you can probably speed things up by pregenerating all x/y/z values in numpy:

import numpy as np

def random_range(n, min, max):
    return min + np.random.random(n) * (max - min)


def fun(x, y, z):
    return (x * y) + z


x = random_range(4000, 4, 8)
y = random_range(4000, -5, 7)
z = random_range(4000, 1, 9)

trial_args = np.stack((x, y, z), axis=-1)
for x, y, z in trial_args:
    print(x, y, z, '=>', fun(x, y, z))

(There might also be a way to have Numpy call fun.)

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks for your answer @AKX . In my case I have to input those three variables in a python based package to get parallel output for 4000 input data points, Is any suggestions? – user105697 Feb 12 '20 at 18:01
  • Not without knowing what that package is. – AKX Feb 12 '20 at 18:09
  • The package is cosmotransitions and I have to input the values of variables inside its generic potential class to initialize the attributes – user105697 Feb 12 '20 at 18:17
  • @user105697 Please ask the question in a form where you have placeholders for this x, y and z then - it'll be infinitely easier to help. – AKX Feb 12 '20 at 18:52
  • I have asked the question https://stackoverflow.com/q/60264394/12540979 in a modified form @AKX – user105697 Feb 17 '20 at 14:18