🚀 Fortuna Random Number Generation Function Documentation
Fortuna is a multi - language random number generation library that supports various programming languages, including Python, C++, and Go. It offers a rich set of probability distribution functions and statistical tools, suitable for scientific computing, data analysis, Monte Carlo simulation, and other fields.
🚀 Quick Start
To start using Fortuna, you first need to install the necessary libraries. Ensure that you have installed the NumPy and Fortuna libraries. These libraries provide a wealth of functions for generating random numbers of different distributions and conducting statistical analysis.
pip install numpy fortuna
Then, import the required libraries in your Python script:
import numpy as np
from fortuna import random, distributions
✨ Features
- Multi - language support: Provides interfaces for multiple languages.
- Rich probability distributions: Includes both continuous and discrete distributions.
- Efficient algorithms: Utilizes proven random number generation algorithms.
- Modular design: Easy to extend and integrate.
📦 Installation
In Python, you can install it using the following command:
pip install fortuna
💻 Usage Examples
Basic Usage
Uniform Distribution
import Fortuna as fr
print(fr.uniform())
Normal Distribution
import Fortuna as fr
print(fr.normal(0, 1))
Coin Toss
import Fortuna as fr
print(fr.coin(0.5))
Advanced Usage
Specific Distribution Functions
Discrete Distributions
Bernoulli Trial
- Description: Generate a Bernoulli random variable.
- Parameters:
p
(float) – Probability of success, default is 0.5.
- Example
print(fr.bernoulli(0.7))
Binomial Distribution
- Description: Generate a binomial random variable.
- Parameters:
n
(int) – Number of trials.
p
(float) – Probability of success in each trial, default is 0.5.
- Example
print(fr.binomial(10, 0.3))
Geometric Distribution
- Description: Generate a geometric random variable representing the number of failures before success.
- Parameters:
p
(float) – Probability of success, default is 0.5.
- Example
print(fr.geometric(0.4))
Negative Binomial Distribution
- Description: Generate a negative binomial random variable representing the number of failures before r successes.
- Parameters:
r
(int) – Number of successes.
p
(float) – Probability of success in each trial, default is 0.5.
- Example
print(fr.negative_binomial(3, 0.7))
Poisson Distribution
- Description: Generate a Poisson random variable representing the number of events occurring in a unit of time.
- Parameters:
lambda
(float) – Average rate, default is 1.0.
- Example
print(fr.poisson(2.5))
Continuous Distributions
Uniform Distribution
- Description: Generate a random variable uniformly distributed in the interval [low, high).
- Parameters:
a
(float) – Lower bound of the interval, default is 0.0.
b
(float) – Upper bound of the interval, default is 1.0.
- Example
print(fr.uniform(0, 5))
Normal Distribution
- Description: Generate a normal random variable, also known as Gaussian distribution.
- Parameters:
mean
(float) – Mean of the distribution, default is 0.0.
std_dev
(float) – Standard deviation of the distribution, default is 1.0.
- Example
print(fr.normal(5, 2))
Exponential Distribution
- Description: Generate an exponential random variable, often used to simulate the waiting time between events.
- Parameters:
lambda
(float) – Average rate, default is 1.0.
- Example
print(fr.exponential(0.5))
Pareto Distribution
- Description: Generate a Pareto random variable, often used to simulate long - tail distributions in natural and social phenomena.
- Parameters:
shape
(float) – Shape parameter of the distribution, default is 2.0.
- Example
print(fr.pareto(2.5))
Weibull Distribution
- Description: Generate a Weibull random variable, often used in reliability engineering and wind speed analysis.
- Parameters:
shape
(float) – Shape parameter of the distribution, default is 2.0.
scale
(float) – Scale parameter of the distribution, default is 1.0.
- Example
print(fr.weibull(3, 2))
Chi - Squared Distribution
- Description: Generate a chi - squared random variable, often used in statistical inference.
- Parameters:
degrees_of_freedom
(int) – Degrees of freedom, default is 1.
- Example
print(fr.chi_squared(5))
F Distribution
- Description: Generate an F random variable, often used in analysis of variance.
- Parameters:
numerator_dof
(int) – Numerator degrees of freedom.
denominator_dof
(int) – Denominator degrees of freedom.
- Example
print(fr.f_distribution(5, 10))
t Distribution
- Description: Generate a t random variable, often used in small - sample statistical inference.
- Parameters:
degrees_of_freedom
(int) – Degrees of freedom, default is 1.
- Example
print(fr.t_distribution(3))
Log - Normal Distribution
- Description: Generate a log - normal random variable, often used to simulate products or growth rates.
- Parameters:
mu
(float) – Mean of the logarithm, default is 0.0.
sigma
(float) – Standard deviation of the logarithm, default is 1.0.
- Example
print(fr.log_normal(0, 0.5))
Cauchy Distribution
- Description: Generate a Cauchy random variable, which is a heavy - tailed distribution.
- Parameters:
location
(float) – Location of the distribution, default is 0.0.
scale
(float) – Scale of the distribution, default is 1.0.
- Example
print(fr.cauchy(0, 2))
Beta Distribution
- Description: Generate a beta random variable, often used to simulate probability density functions.
- Parameters:
alpha
(float) – First shape parameter, default is 1.0.
beta
(float) – Second shape parameter, default is 1.0.
- Example
print(fr.beta(2, 5))
Statistical Tools
Random Sampling
Sampling Without Replacement
import numpy as np
population = np.array([10, 20, 30, 40, 50])
print(fr.sample(population, 3))
Stratified Sampling
population = {'A': [1, 2, 3], 'B': [4, 5, 6]}
print(fr.stratified_sample(population, 2))
Hypothesis Testing
Kolmogorov - Smirnov Test
sample = [1.2, 1.5, 2.0, 2.5, 3.0]
print(fr.kolmogorov_smirnov_test(sample))
Shapiro - Wilk Test
sample = [1.2, 1.5, 2.0, 2.5, 3.0]
print(fr.shapiro_wilk_test(sample))
Statistical Modeling
Linear Regression
import pandas as pd
data = {'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 6, 7]}
df = pd.DataFrame(data)
model = fr.linear_regression(df, 'x', 'y')
print(model.summary())
Logistic Regression
data = {'x': [1, 2, 3, 4, 5], 'y': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)
model = fr.logistic_regression(df, 'x', 'y')
print(model.summary())
Examples
Monte Carlo Simulation
def roll_dice():
return np.random.randint(1, 7)
results = [roll_dice() for _ in range(10000)]
print(f"Mean: {np.mean(results)}, Variance: {np.var(results)}")
Risk Management
returns = np.random.normal(loc=0.05, scale=0.1, size=1000)
portfolio_value = 1000 * (1 + returns).cumprod()
print(f"Expected Return: {np.mean(returns)*100}%, Volatility: {np.std(returns)*100}%")
import matplotlib.pyplot as plt
plt.plot(portfolio_value)
plt.show()
Quality Control
sample_size = 50
defects = np.random.binomial(n=10, p=0.05, size=100)
control_limits = fr.control_limits(sample_size, defects)
print(f"Upper Control Limit: {control_limits[0]}, Lower Control Limit: {control_limits[1]}")
import matplotlib.pyplot as plt
plt.plot(defects)
plt.axhline(y=control_limits[0], color='red')
plt.axhline(y=control_limits[1], color='red')
plt.show()
Step - by - Step Guide for Advanced Usage
Step 3: Generate Uniformly Distributed Random Numbers
Use the random.uniform
function to generate random numbers uniformly distributed in the interval [0,1).
single_random = random.uniform()
print(f"Single Uniform Random Number: {single_random}")
array_random = random.uniform(size=5)
print("\nArray of Uniform Random Numbers:")
print(array_random)
Step 4: Generate Normally Distributed Random Numbers
Use the random.normal
function to generate random numbers from a normal distribution with mean 0 and standard deviation 1.
single_normal = random.normal()
print(f"\nSingle Normal Random Number: {single_normal}")
array_normal = random.normal(size=5)
print("\nArray of Normal Random Numbers:")
print(array_normal)
Step 5: Generate Random Numbers from Custom Distributions
You can generate random numbers from custom distributions by passing a probability mass function (PMF) or probability density function (PDF).
pmf = np.array([1/6, 1/6, 1/6, 1/6, 1/6, 1/6])
custom_discrete = distributions.Categorical(pmf)
discrete_random = custom_discrete.sample(size=5)
print("\nCustom Discrete Random Numbers:")
print(discrete_random)
lambda_param = 0.5
pdf = lambda x: lambda_param * np.exp(-lambda_param * x)
custom_continuous = distributions.CustomDistribution(pdf)
continuous_random = custom_continuous.sample(size=5)
print("\nCustom Continuous Random Numbers:")
print(continuous_random)
Step 6: Conduct Statistical Simulations
Utilize the generated random numbers to conduct various statistical simulations, such as Monte Carlo integration, risk analysis, or hypothesis testing.
def monte_carlo_pi(n_samples):
random_points = random.uniform(low=-1, high=1, size=(n_samples, 2))
inside_circle = (random_points[:, 0]**2 + random_points[:, 1]**2) <= 1
return np.mean(inside_circle) * 4
n_samples = 10000
pi_estimation = monte_carlo_pi(n_samples)
print(f"\nMonte Carlo Estimation of π with {n_samples} samples: {pi_estimation}")
Step 7: Visualize the Results
Use matplotlib to visualize the generated random numbers or simulation results.
import matplotlib.pyplot as plt
plt.hist(array_normal, bins=15, density=True, alpha=0.6, color='b')
plt.title('Normal Distribution Sample')
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.show()
points = random.uniform(low=-1, high=1, size=(n_samples, 2))
inside = points[points[:, 0]**2 + points[:, 1]**2 <= 1]
outside = points[points[:, 0]**2 + points[:, 1]**2 > 1]
plt.scatter(inside[:, 0], inside[:, 1], color='blue', alpha=0.5)
plt.scatter(outside[:, 0], outside[:, 1], color='red', alpha=0.5)
plt.title('Monte Carlo Integration for π')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Step 8: Result Analysis
Based on the generated random numbers and simulation results, conduct statistical analysis, such as calculating the mean, variance, or other required statistics, and adjust the parameters or algorithms as needed.
📚 Documentation
Random number generation and statistical simulation play important roles in multiple fields such as scientific research, engineering design, and financial analysis. By using libraries like NumPy and Fortuna, we can efficiently perform data sampling and modeling, thereby providing reliable support for decision - making.
Summary
Through the above steps, you can effectively utilize the NumPy and Fortuna libraries to generate random numbers of various distributions and conduct complex statistical simulations. This is very useful for scientific research, engineering design, financial modeling, and other fields, helping you make more informed data - driven decisions.