Contact
Back to Home

Can you construct a function that generates a random normal distribution and then plot it?

Featured Answer

Question Analysis

The question asks you to create a function that generates a random normal distribution and then plots it. Here's a breakdown of what is required:

  1. Random Normal Distribution: This refers to a data set that follows a normal (Gaussian) distribution, characterized by its bell-shaped curve. It is defined by its mean (average) and standard deviation (spread).

  2. Function Construction: You need to write a function in a programming language (commonly Python for such tasks) that can generate random numbers following a normal distribution.

  3. Plotting: Once the data is generated, you are required to plot it to visualize the distribution. This is typically done using a plotting library.

  4. Tools to Use: In Python, you can use the numpy library to generate the normal distribution and matplotlib to plot it.

Answer

import numpy as np
import matplotlib.pyplot as plt

def generate_and_plot_normal_distribution(mean=0, std_dev=1, num_samples=1000):
    """
    Generates a random normal distribution and plots it.

    Parameters:
    - mean: The mean or average of the normal distribution.
    - std_dev: The standard deviation of the normal distribution.
    - num_samples: The number of random samples to generate.

    Returns:
    - None: This function will display a plot.
    """
    # Generate random normal distribution
    data = np.random.normal(loc=mean, scale=std_dev, size=num_samples)
    
    # Plotting the distribution
    plt.figure(figsize=(10, 6))
    plt.hist(data, bins=30, density=True, alpha=0.6, color='g')
    
    # Plotting the normal distribution curve
    min_xlim, max_xlim = plt.xlim()
    x = np.linspace(min_xlim, max_xlim, 100)
    p = (1 / (np.sqrt(2 * np.pi) * std_dev)) * np.exp(-0.5 * ((x - mean) / std_dev) ** 2)
    plt.plot(x, p, 'k', linewidth=2)

    # Adding titles and labels
    plt.title('Random Normal Distribution')
    plt.xlabel('Value')
    plt.ylabel('Probability Density')

    # Show plot
    plt.show()

# Example usage
generate_and_plot_normal_distribution(mean=0, std_dev=1, num_samples=1000)

Explanation:

  • Libraries Used:

    • numpy is used to generate random numbers with a normal distribution.
    • matplotlib.pyplot is used to create a histogram and plot the probability density function.
  • Function Parameters:

    • mean: Average value of the distribution. Default is 0.
    • std_dev: Standard deviation, representing the spread. Default is 1.
    • num_samples: Number of samples to generate. Default is 1000.
  • Plotting:

    • A histogram of the random data is plotted.
    • The probability density function is overlaid to show the expected normal distribution shape.

This code snippet provides a clear, professional, and concise way to generate and plot a random normal distribution using Python.