import random
import numpy as np
import matplotlib.pyplot as plt
# Define the task information
tasks = {
'Task 1': {'Duration': [2, 4, 6], 'Probs': [0.3, 0.5, 0.2], 'Cost': [1000, 1500, 2000]},
'Task 2': {'Duration': [4, 6, 8], 'Probs': [0.2, 0.4, 0.4], 'Cost': [2000, 2500, 3000]},
'Task 3': {'Duration': [3, 5, 7], 'Probs': [0.5, 0.3, 0.2], 'Cost': [1500, 2000, 2500]},
}
n_iterations = 10000
durations = []
costs = []
# Run the Monte Carlo simulations
for _ in range(n_iterations):
total_duration = 0
total_cost = 0
for task in tasks.values():
duration_choice = random.choices(task['Duration'], task['Probs'])[0]
index = task['Duration'].index(duration_choice)
cost_choice = task['Cost'][index]
total_duration += duration_choice
total_cost += cost_choice
durations.append(total_duration)
costs.append(total_cost)
# Analyze and display the results
average_duration = np.mean(durations)
std_dev_duration = np.std(durations)
average_cost = np.mean(costs)
std_dev_cost = np.std(costs)
print(f"Average Project Duration: {average_duration:.2f} days")
print(f"Duration Standard Deviation: {std_dev_duration:.2f} days")
print(f"Average Project Cost: ${average_cost:.2f}")
print(f"Cost Standard Deviation: ${std_dev_cost:.2f}")
plt.figure(figsize=(14, 5))
plt.subplot(1, 2, 1)
plt.hist(durations, bins='auto', color='blue', alpha=0.7)
plt.xlabel('Project Duration (days)')
plt.ylabel('Frequency')
plt.title(f'Monte Carlo Simulation - Duration\nMean: {average_duration:.2f} days, Std Dev: {std_dev_duration:.2f} days')
plt.subplot(1, 2, 2)
plt.hist(costs, bins='auto', color='green', alpha=0.7)
plt.xlabel('Project Cost ($)')
plt.ylabel('Frequency')
plt.title(f'Monte Carlo Simulation - Cost\nMean: ${average_cost:.2f}, Std Dev: ${std_dev_cost:.2f}')
plt.show()
This script defines three tasks with their respective durations and costs, and runs 10000 Monte Carlo simulation iterations. It calculates the average and standard deviation for project duration and cost and then displays the results in histograms.