Skip to content

Improve Efficiency of Harmonic Mean Calculation #2

@SaFE-APIOpt

Description

@SaFE-APIOpt

harmonic_mean_value = stats.hmean(data)

Current Code:

def harmonic_mean(data):
    if (data <= 0).any().any():
        st.warning("⚠️ Harmonic mean is not defined for data with negative or zero values.")
    else:
        harmonic_mean_value = stats.hmean(data)
        st.write("Harmonic Mean:", harmonic_mean_value)

Suggested Optimization:

def harmonic_mean(data):
    if (data <= 0).any().any():
        st.warning("⚠️ Harmonic mean is not defined for data with negative or zero values.")
    else:
        harmonic_mean_value = len(data) / np.sum(1.0 / data)
        st.write("Harmonic Mean:", harmonic_mean_value)

The function scipy.stats.hmean is designed for robustness, with internal checks for multidimensional inputs, type casting, and invalid values.This custom implementation avoids the overhead of additional checks, leading to better runtime performance and lower memory usage, especially for large arrays. It is mathematically equivalent in this safe context and significantly faster.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions