Practical Applications
Simulation and Modeling
Monte Carlo Simulation
import random
import math
def estimate_pi(num_points):
inside_circle = 0
total_points = num_points
for _ in range(total_points):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
if x*x + y*y <= 1:
inside_circle += 1
pi_estimate = 4 * inside_circle / total_points
return pi_estimate
print(f"Estimated Pi: {estimate_pi(100000)}")
Game Development
Dice Rolling Simulator
def roll_dice(num_dice=2, sides=6):
return [random.randint(1, sides) for _ in range(num_dice)]
def game_simulation():
player_roll = roll_dice()
computer_roll = roll_dice()
print(f"Player rolls: {player_roll}")
print(f"Computer rolls: {computer_roll}")
return sum(player_roll) > sum(computer_roll)
print("Game Result:", game_simulation())
Data Augmentation
Random Data Generation
def generate_test_data(num_samples=10):
return [
{
'age': random.randint(18, 65),
'salary': random.uniform(30000, 100000),
'department': random.choice(['HR', 'IT', 'Sales', 'Marketing'])
}
for _ in range(num_samples)
]
test_data = generate_test_data()
print(test_data)
Randomization Workflow
graph TD
A[Start Randomization] --> B{Choose Application}
B --> |Simulation| C[Monte Carlo Method]
B --> |Game Development| D[Probability Calculation]
B --> |Data Generation| E[Random Data Creation]
C --> F[Generate Random Points]
D --> G[Roll Dice/Generate Outcomes]
E --> H[Create Random Datasets]
Application Scenarios
Domain |
Randomization Technique |
Use Case |
Scientific Research |
Monte Carlo Simulation |
Complex system modeling |
Game Development |
Probabilistic Outcomes |
Game mechanics |
Machine Learning |
Data Augmentation |
Training dataset expansion |
Cybersecurity |
Penetration Testing |
Random vulnerability scanning |
Machine Learning Applications
def split_dataset(data, train_ratio=0.8):
random.shuffle(data)
split_index = int(len(data) * train_ratio)
train_data = data[:split_index]
test_data = data[split_index:]
return train_data, test_data
## Example usage
dataset = list(range(100))
train, test = split_dataset(dataset)
Cryptographic Applications
import secrets
def generate_secure_token(length=32):
return secrets.token_hex(length)
secure_token = generate_secure_token()
print("Secure Token:", secure_token)
- Use
random.SystemRandom()
for cryptographic randomness
- Leverage
numpy
for large-scale random generation
- Cache random number generators for repeated use
Error Handling and Validation
def validate_random_generation(func):
try:
result = func()
print(f"Random generation successful: {result}")
except Exception as e:
print(f"Randomization error: {e}")
validate_random_generation(lambda: random.randint(1, 10))
LabEx Recommendations
- Understand context-specific randomization needs
- Choose appropriate random generation method
- Consider performance and security implications
- Test randomization thoroughly in different scenarios