本文整理汇总了Python中random.uniform函数的典型用法代码示例。如果您正苦于以下问题:Python uniform函数的具体用法?Python uniform怎么用?Python uniform使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了uniform函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: genRandSubIntervals
def genRandSubIntervals():
intervals = []
for i in range(10):
start = random.uniform(0.0, 1.0)
end = random.uniform(start, 1.0)
intervals.append((start, end))
return intervals
开发者ID:GlennRC,项目名称:Algorithms,代码行数:7,代码来源:main.py
示例2: splitter
def splitter():
splitField = ["ra", "dec", "dist", "mag", "absmag", "x", "y", "z", "vx", "vy", "vz"][random.randint(0, 10)]
if splitField == "ra":
splitValue = random.uniform(1, 23)
elif splitField == "dec":
splitValue = random.uniform(-87, 87)
elif splitField == "dist":
splitValue = math.exp(random.gauss(5.5, 1))
elif splitField == "mag":
splitValue = random.gauss(8, 1)
elif splitField == "absmag":
splitValue = random.gauss(2, 2)
elif splitField == "x":
splitValue = math.exp(random.gauss(5, 1)) * (1 if random.randint(0, 1) == 1 else -1)
elif splitField == "y":
splitValue = math.exp(random.gauss(5, 1)) * (1 if random.randint(0, 1) == 1 else -1)
elif splitField == "z":
splitValue = math.exp(random.gauss(5, 1)) * (1 if random.randint(0, 1) == 1 else -1)
elif splitField == "vx":
splitValue = math.exp(random.gauss(-12, 1)) * (1 if random.randint(0, 1) == 1 else -1)
elif splitField == "vy":
splitValue = math.exp(random.gauss(-12, 1)) * (1 if random.randint(0, 1) == 1 else -1)
elif splitField == "vz":
splitValue = math.exp(random.gauss(-12, 1)) * (1 if random.randint(0, 1) == 1 else -1)
return splitField, splitValue
开发者ID:ajutzeler,项目名称:hadrian,代码行数:25,代码来源:hipparcos_numerical_prepare.py
示例3: init_random_generation
def init_random_generation(items):
generation = []
for i in range(items):
theta = random.uniform(15, 180) * math.pi / 180
v = random.uniform(2, 20)
generation.append((theta, v))
return generation
开发者ID:doctorlove,项目名称:paperbag,代码行数:7,代码来源:ga.py
示例4: direct_pi
def direct_pi(N):
n_hits = 0
for i in range(N):
x, y = random.uniform(-1.0, 1.0), random.uniform(-1.0, 1.0)
if x ** 2 + y ** 2 < 1.0:
n_hits += 1
return n_hits
开发者ID:M0nd4,项目名称:statistical-mechanics-ens,代码行数:7,代码来源:homework_w1_q_a1.py
示例5: randPayoff
def randPayoff():
global M
global neighborhood
global neighbSize
# Randomizing Payoff
for x in range(0, len(ch)):
playingZeroMax = 0
playingOneMax = 0
playingZeroMin = 0
playingOneMin = 0
# Randomizing Payoff
for y in range(0, neighbSize[x]):
M[(x, neighborhood[x][y])][0][0] = round(random.uniform(0.0, 1.0), 3)
M[(x, neighborhood[x][y])][0][1] = round(random.uniform(0.0, 1.0), 3)
playingZeroMax += max(M[(x, neighborhood[x][y])][0][0], M[(x, neighborhood[x][y])][0][1])
playingZeroMin += min(M[(x, neighborhood[x][y])][0][0], M[(x, neighborhood[x][y])][0][1])
M[(x, neighborhood[x][y])][1][0] = round(random.uniform(0.0, 1.0), 3)
M[(x, neighborhood[x][y])][1][1] = round(random.uniform(0.0, 1.0), 3)
playingOneMax += max(M[(x, neighborhood[x][y])][1][0], M[(x, neighborhood[x][y])][1][1])
playingOneMin += min(M[(x, neighborhood[x][y])][1][0], M[(x, neighborhood[x][y])][1][1])
playingMax = max(playingOneMax, playingZeroMax)
playingMin = min(playingOneMin, playingZeroMin)
# Normalizing Payoff Matrix
for y in range(0, neighbSize[x]):
M[(x, neighborhood[x][y])][0][0] = round((M[(x, neighborhood[x][y])][0][0]-playingMin/neighbSize[x])/(playingMax-playingMin/neighbSize[x]), 3)
M[(x, neighborhood[x][y])][0][1] = round((M[(x, neighborhood[x][y])][0][1]-playingMin/neighbSize[x])/(playingMax-playingMin/neighbSize[x]), 3)
M[(x, neighborhood[x][y])][1][0] = round((M[(x, neighborhood[x][y])][1][0]-playingMin/neighbSize[x])/(playingMax-playingMin/neighbSize[x]), 3)
M[(x, neighborhood[x][y])][1][1] = round((M[(x, neighborhood[x][y])][1][1]-playingMin/neighbSize[x])/(playingMax-playingMin/neighbSize[x]), 3)
开发者ID:liruiqi777,项目名称:20160724_epsilon-NashEquilibrium,代码行数:33,代码来源:FPTASwNormHardness.py
示例6: _genRhoWidth
def _genRhoWidth(psr):
"""Calculate the opening angle of pulsar, and the beamwidth.
Based on model outlined in Smits et al. 2009"""
# cut off period for model
perCut = 30.0
# calclate rho
randfactor = random.uniform(-.15, .15)
if psr.period > perCut:
rho = _rhoLaw(psr.period)
else:
rho = _rhoLaw(perCut)
logrho = math.log10(rho) + randfactor
rho = 10. ** logrho
# generate beta and pulse width
beta = random.uniform(-1, 1) * rho
width = _sindegree(0.5 * rho) * _sindegree(0.5 * rho)
width = width - (_sindegree(0.5 * beta) * _sindegree(0.5 * beta))
width = width / (_sindegree(psr.alpha) * _sindegree(psr.alpha + beta))
if width < 0.0 or width > 1.0:
width = 0.0
rho = 0.0
else:
width = math.sqrt(width)
# convert the width into degrees 0 -> 360 (ie. 90*4)
width = math.degrees(math.asin(width))*4.0
return rho, width
开发者ID:samb8s,项目名称:PsrPopPy,代码行数:32,代码来源:populate.py
示例7: insertHapticSensorsRandom
def insertHapticSensorsRandom(self):
"""insert haptic sensors at random locations"""
self.sensorGroupName = 'haptic'
for _ in range(5):
self.insertHapticSensor(dx=random.uniform(-0.65, 0.65), dz=random.uniform(-0.4, 0.2))
##self.insertHapticSensor(dx=-0.055)
return
开发者ID:evansneath,项目名称:pybrain,代码行数:7,代码来源:xodetools.py
示例8: monte_carlo
def monte_carlo(beta, cubic, quartic):
beta = 2.0
N = 2 ** 5
dtau = beta / N
delta = 1.0
n_steps = int(10 ** 7)
X = np.zeros([n_steps, N])
x = [0.0] * N
for step in range(n_steps):
k = random.randint(0, N - 1)
knext, kprev = (k + 1) % N, (k - 1) % N
x_new = x[k] + random.uniform(-delta, delta)
old_weight = (
rho_free(x[knext], x[k], dtau) * rho_free(x[k], x[kprev], dtau) * math.exp(-dtau * V(x[k], cubic, quartic))
)
new_weight = (
rho_free(x[knext], x_new, dtau)
* rho_free(x_new, x[kprev], dtau)
* math.exp(-dtau * V(x_new, cubic, quartic))
)
if random.uniform(0.0, 1.0) < new_weight / old_weight:
x[k] = x_new
X[step, :] = x
if step % 10000 == 0:
print("step %d / %d" % (step, n_steps))
return X
开发者ID:vsilv,项目名称:smag,代码行数:26,代码来源:C2.py
示例9: test_validate_point_count_called
def test_validate_point_count_called(self):
import random
with mock.patch("course.page.base.validate_point_count")\
as mock_validate_point_count,\
mock.patch("course.page.base.get_auto_feedback")\
as mock_get_auto_feedback:
mock_validate_point_count.side_effect = lambda x: x
mock_get_auto_feedback.side_effect = lambda x: x
for i in range(10):
correctness = random.uniform(0, 15)
feedback = "some feedback"
AnswerFeedback(correctness, feedback)
mock_validate_point_count.assert_called_once_with(correctness)
# because feedback is not None
self.assertEqual(mock_get_auto_feedback.call_count, 0)
mock_validate_point_count.reset_mock()
for i in range(10):
correctness = random.uniform(0, 15)
AnswerFeedback(correctness)
# because get_auto_feedback is mocked, the call_count of
# mock_validate_point_count is only once
mock_validate_point_count.assert_called_once_with(correctness)
mock_validate_point_count.reset_mock()
# because feedback is None
self.assertEqual(mock_get_auto_feedback.call_count, 1)
mock_get_auto_feedback.reset_mock()
AnswerFeedback(correctness=None)
mock_validate_point_count.assert_called_once_with(None)
开发者ID:ishitatsuyuki,项目名称:relate,代码行数:34,代码来源:test_generic.py
示例10: add_exhaust_to_face
def add_exhaust_to_face(bm, face):
if not face.is_valid:
return
# The more square the face is, the more grid divisions it might have
num_cuts = randint(1, int(4 - get_aspect_ratio(face)))
result = bmesh.ops.subdivide_edges(bm,
edges=face.edges[:],
cuts=num_cuts,
fractal=0.02,
use_grid_fill=True)
exhaust_length = uniform(0.1, 0.2)
scale_outer = 1 / uniform(1.3, 1.6)
scale_inner = 1 / uniform(1.05, 1.1)
for face in result['geom']:
if isinstance(face, bmesh.types.BMFace):
if is_rear_face(face):
face.material_index = Material.hull_dark
face = extrude_face(bm, face, exhaust_length)
scale_face(bm, face, scale_outer, scale_outer, scale_outer)
extruded_face_list = []
face = extrude_face(bm, face, -exhaust_length * 0.9, extruded_face_list)
for extruded_face in extruded_face_list:
extruded_face.material_index = Material.exhaust_burn
scale_face(bm, face, scale_inner, scale_inner, scale_inner)
开发者ID:HackNuts,项目名称:SpaceshipGenerator,代码行数:26,代码来源:spaceship_generator.py
示例11: testSolveAndCall
def testSolveAndCall( self ) :
random.seed( 0 )
for i in range( 0, 100 ) :
s = IECore.Splineff()
x = 0
for i in range( 0, 40 ) :
s[x] = random.uniform( 0, 10 )
x += 1 + random.uniform( 0, 1 )
xv = s.keys()
yv = s.values()
for i in range( 0, 1000 ) :
# select a segment
seg = int(random.uniform( 0, int(len(xv) / 4) ))
seg -= seg % s.basis.step
# evaluate an x,y point on the curve directly
# ourselves
t = i / 1000.0
c = s.basis.coefficients( t )
x = xv[seg+0] * c[0] + xv[seg+1] * c[1] + xv[seg+2] * c[2] + xv[seg+3] * c[3]
y = yv[seg+0] * c[0] + yv[seg+1] * c[1] + yv[seg+2] * c[2] + yv[seg+3] * c[3]
# then check that solving for x gives y
yy = s( x )
self.assertAlmostEqual( yy, y, 3 )
开发者ID:ImageEngine,项目名称:cortex,代码行数:32,代码来源:SplineTest.py
示例12: generate_asteroid
def generate_asteroid(self, now):
# Check if it's time to create a new object
if (now > self.next_gen_time):
# Create a new object
# Select a random item from the list, and
# pull it out of the list
# Note: It should have been cloned, but there is a problem
# with clone()
ast_num = random.randint(0,len(self.asteroid_model_list)-2)
nobj = self.asteroid_model_list[ast_num]
del self.asteroid_model_list[ast_num]
# Select an incident angle and speed
azimuth = random.uniform(*AZIMUTH_RANGE)
incl = random.uniform(*INCLINATION_RANGE)
speed = random.uniform(*SPEED_RANGE)
# Create the asteroid object
ast = Asteroid(nobj, azimuth, incl, speed, now, self.explosion_shader, self.regular_shader)
# Calculate the next generation time
self.calc_next_gen_time()
# Return the new asteroid
return ast
else:
# Do not create anything
return None
开发者ID:cyberaa,项目名称:astrogun,代码行数:30,代码来源:asteroids.py
示例13: __init__
def __init__(self, pos):
self.pos = pos
self.life = 10 + int(random.random() * 2)
self.move = Vec2D(random.uniform(-2.5, 2.5), random.uniform(-2.5, 0.0))
self.surf = resman.get("game.sparkle_surf")
width, height = self.surf.get_size()
self.center = Vec2D(width / 2, height / 2)
开发者ID:mdtrooper,项目名称:MysticMine,代码行数:7,代码来源:pickupsview.py
示例14: test_geopoint_to_native
def test_geopoint_to_native():
geo = GeoPointType(required=True)
with pytest.raises(ConversionError):
native = geo.to_native((10,))
with pytest.raises(ConversionError):
native = geo.to_native({'1':'-20', '2': '18'})
with pytest.raises(ConversionError):
native = geo.to_native(['-20', '18'])
with pytest.raises(ConversionError):
native = geo.to_native('-20, 18')
class Point(object):
def __len__(self):
return 2
with pytest.raises(ConversionError):
native = geo.to_native(Point())
native = geo.to_native([89, -12])
assert native == [89, -12]
latitude = random.uniform(-90, 90)
longitude = random.uniform(-180, 180)
point = [latitude, longitude]
native = geo.to_native(point)
assert native == point
开发者ID:dmitryTsatsarin,项目名称:schematics,代码行数:32,代码来源:test_types.py
示例15: draw_stochastic2
def draw_stochastic2(s):
return draw_generic(RhinoTurtle(), {
'a': lambda t: t.forward(random.uniform(10,20)),
'b': lambda t: t.right(random.uniform(0, 90)),
'c': lambda t: t.left(random.uniform(0, 90)),
}, s)
开发者ID:chirs,项目名称:fractal,代码行数:7,代码来源:draw.py
示例16: test_serialisation
def test_serialisation(self):
""" Test saving and then reloading a test spectra.
"""
test_decays = 10
test_spectra = spectra.Spectra("Test", test_decays)
for x in range(0, test_decays):
energy = random.uniform(0, test_spectra._energy_high)
radius = random.uniform(0, test_spectra._radial_high)
time = random.uniform(0, test_spectra._time_high)
test_spectra.fill(energy, radius, time)
store.dump("test.hdf5", test_spectra)
loaded_spectra = store.load("test.hdf5")
self.assertTrue(loaded_spectra.sum() == test_decays)
self.assertTrue(numpy.array_equal(test_spectra._data, loaded_spectra._data))
self.assertTrue(test_spectra._energy_low == loaded_spectra._energy_low)
self.assertTrue(test_spectra._energy_high == loaded_spectra._energy_high)
self.assertTrue(test_spectra._energy_bins == loaded_spectra._energy_bins)
self.assertTrue(test_spectra._energy_width == loaded_spectra._energy_width)
self.assertTrue(test_spectra._radial_low == loaded_spectra._radial_low)
self.assertTrue(test_spectra._radial_high == loaded_spectra._radial_high)
self.assertTrue(test_spectra._radial_bins == loaded_spectra._radial_bins)
self.assertTrue(test_spectra._radial_width == loaded_spectra._radial_width)
self.assertTrue(test_spectra._time_low == loaded_spectra._time_low)
self.assertTrue(test_spectra._time_high == loaded_spectra._time_high)
self.assertTrue(test_spectra._time_bins == loaded_spectra._time_bins)
self.assertTrue(test_spectra._time_width == loaded_spectra._time_width)
self.assertTrue(test_spectra._num_decays == loaded_spectra._num_decays)
开发者ID:Mark--S,项目名称:echidna,代码行数:29,代码来源:test_store.py
示例17: __init__
def __init__(self, height, width):
"""Constructor will randomize the polygon."""
# Dimensions of src image
self.height = height
self.width = width
# Random constants
self.maxSep = (height + width) / self.__class__.MAX_SEP_DENOM # TODO XXX REMOVE
# Anchor points control translation
self.xAnchor = random.randint(-width, width)
self.yAnchor = random.randint(-height, height)
# Each polygon point, relative to the anchor points
self.xPoints = []
self.yPoints = []
if len(self.xPoints) == 0:
self.initPoints() # Don't perform in copying
# Other Geometry/LinearAlg operations
self.xGrowth = random.uniform(self.__class__.MIN_GROWTH,
self.__class__.MAX_GROWTH)
self.yGrowth = random.uniform(self.__class__.MIN_GROWTH,
self.__class__.MAX_GROWTH)
self.rotation = 0 # TODO, probably difficult
self.affine = 0 # TODO
开发者ID:echelon,项目名称:genetic-python,代码行数:28,代码来源:Polygon.py
示例18: processAlgorithm
def processAlgorithm(self, parameters, context, feedback):
spacing = self.parameterAsDouble(parameters, self.SPACING, context)
inset = self.parameterAsDouble(parameters, self.INSET, context)
randomize = self.parameterAsBool(parameters, self.RANDOMIZE, context)
isSpacing = self.parameterAsBool(parameters, self.IS_SPACING, context)
crs = self.parameterAsCrs(parameters, self.CRS, context)
extent = self.parameterAsExtent(parameters, self.EXTENT, context, crs)
fields = QgsFields()
fields.append(QgsField('id', QVariant.Int, '', 10, 0))
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, QgsWkbTypes.Point, crs)
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
if randomize:
seed()
area = extent.width() * extent.height()
if isSpacing:
pSpacing = spacing
else:
pSpacing = sqrt(area / spacing)
f = QgsFeature()
f.initAttributes(1)
f.setFields(fields)
count = 0
total = 100.0 / (area / pSpacing)
y = extent.yMaximum() - inset
extent_geom = QgsGeometry.fromRect(extent)
extent_engine = QgsGeometry.createGeometryEngine(extent_geom.constGet())
extent_engine.prepareGeometry()
while y >= extent.yMinimum():
x = extent.xMinimum() + inset
while x <= extent.xMaximum():
if feedback.isCanceled():
break
if randomize:
geom = QgsGeometry().fromPointXY(QgsPointXY(
uniform(x - (pSpacing / 2.0), x + (pSpacing / 2.0)),
uniform(y - (pSpacing / 2.0), y + (pSpacing / 2.0))))
else:
geom = QgsGeometry().fromPointXY(QgsPointXY(x, y))
if extent_engine.intersects(geom.constGet()):
f.setAttribute('id', count)
f.setGeometry(geom)
sink.addFeature(f, QgsFeatureSink.FastInsert)
x += pSpacing
count += 1
feedback.setProgress(int(count * total))
y = y - pSpacing
return {self.OUTPUT: dest_id}
开发者ID:tcoupin,项目名称:QGIS,代码行数:60,代码来源:RegularPoints.py
示例19: qtstart
def qtstart():
global ctimer, wxtimer, temptimer
global manager
global objradar1
global objradar2
global objradar3
global objradar4
getallwx()
gettemp()
r1 = random.uniform(1000,10000)
r2 = random.uniform(1000,10000)
objradar1.start(1000*5*60+r1)
objradar2.start(1000*5*60+r1)
objradar3.start(1000*5*60+r2)
objradar4.start(1000*5*60+r2)
ctimer = QtCore.QTimer()
ctimer.timeout.connect(tick)
ctimer.start(1000)
wxtimer = QtCore.QTimer()
wxtimer.timeout.connect(getallwx)
wxtimer.start(1000*10*60+random.uniform(1000,10000))
temptimer = QtCore.QTimer()
temptimer.timeout.connect(gettemp)
temptimer.start(1000*10*60+random.uniform(1000,10000))
开发者ID:NazioByte,项目名称:PiClock,代码行数:30,代码来源:PyQtPiClock.py
示例20: getRandomPosition
def getRandomPosition(self):
"""
Return a random position inside the room.
returns: a Position object.
"""
return Position(random.uniform(0, self.width), random.uniform(0, self.height))
开发者ID:shchen,项目名称:edx_intro_to_cs,代码行数:7,代码来源:ps7.py
注:本文中的random.uniform函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论