Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.3 kB
3
Indexable
Never
import math

def calculate_dispersion(midpoints, frequencies):
    n = sum(frequencies)
    mean = sum(midpoints[i] * frequencies[i] for i in range(len(midpoints))) / n

    # Variance
    var = sum(((midpoints[i] - mean) ** 2) * frequencies[i] for i in range(len(midpoints))) / n

    # Standard Deviation
    std = math.sqrt(var)

    # Quartile Deviation
    cumulative_freq = 0
    q1 = n // 4
    q3 = 3 * n // 4
    for i in range(len(midpoints)):
        cumulative_freq += frequencies[i]
        if cumulative_freq >= q1:
            q1_val = midpoints[i]
            break
    for i in range(len(midpoints)):
        cumulative_freq += frequencies[i]
        if cumulative_freq >= q3:
            q3_val = midpoints[i]
            break
    q_deviation = (q3_val - q1_val) / 2

    # Mean Deviation
    mean_dev = sum(abs(midpoints[i] - mean) * frequencies[i] for i in range(len(midpoints))) / n

    return var, std, q_deviation, mean_dev

# Example data
midpoints = [10, 20, 30, 40, 50]
frequencies = [5, 8, 12, 7, 3]

var, std, q_dev, mean_dev = calculate_dispersion(midpoints, frequencies)

print(f"Variance: {var}")
print(f"Standard Deviation: {std}")
print(f"Quartile Deviation: {q_dev}")
print(f"Mean Deviation: {mean_dev}")
Leave a Comment