How to do a random Monte Carlo scan and getting the outputs in a data file

北慕城南 提交于 2021-02-17 07:13:04

问题


I have some python program let's say 'Test.py' it has a class and inside this in the init I have to introduce three random variables.

import math
class Vector():
def __init__(self,vx,vy,vz):
    self.x=vx
    self.y=vy
    self.z=vz

def norm(self):
    xx=self.x**2
    yy=self.y**2
    zz=self.z**2
    return math.sqrt(xx+yy+zz)

Now I made a run file 'Testrun.py' which calls this file and then for each dataset it produces one result

import math
import numpy as np

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

model=Test.Vector(x,y,z)

x=random_range(20,2,9)
y=random_range(20,2,9)
z=random_range(20,2,9)

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

Now I want to store only the results which gives the 'norm'>5 and want to print the inputs and outputs in a data file


回答1:


Keeping the same 'Test.py'

import math
class Vector():
 def __init__(self,vx,vy,vz):
    self.x=vx
    self.y=vy
    self.z=vz

 def norm(self):
    xx=self.x**2
    yy=self.y**2
    zz=self.z**2
    return math.sqrt(xx+yy+zz)

We have to put the output condition by a if loop

import math
import numpy as np

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

x=random_range(20,2,9)
y=random_range(20,2,9)
z=random_range(20,2,9)

trial_args = np.stack((x, y, z), axis=-1)
for x, y, z in trial_args:
    model=Test.Vector(x,y,z)
    if model.norm()>5:
       print(x, y, z, '=>', model.norm())


来源:https://stackoverflow.com/questions/60264394/how-to-do-a-random-monte-carlo-scan-and-getting-the-outputs-in-a-data-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!