Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Incorrect Results in Math Utility Function #5

Open
arjun-katonic-ai opened this issue Nov 22, 2024 · 4 comments
Open

[Bug]: Incorrect Results in Math Utility Function #5

arjun-katonic-ai opened this issue Nov 22, 2024 · 4 comments

Comments

@arjun-katonic-ai
Copy link

arjun-katonic-ai commented Nov 22, 2024

The calculate_average() function in the Math Utilities module produces incorrect results when processing datasets that include zero or negative numbers. This happens due to improper handling of edge cases in the formula and division errors caused by empty datasets or filters that exclude valid values.

Reproduction Steps:

  1. Pass a list of integers containing zeros or negatives to the calculate_average() function.
    • Example: calculate_average([5, 0, -3, 7]).
  2. Observe the output.
    • Expected Output: The function should return the correct average considering all valid numbers in the list.
    • Actual Output: The function returns incorrect results or raises a division error when invalid cases are encountered.

Problematic Code Example:

def calculate_average(numbers):
    return sum(numbers) / len(numbers)

Issues Identified:

  1. Zero and Negative Numbers: The function does not account for cases where negative or zero values should be excluded based on business rules.
  2. Division by Zero: The function crashes when the input list is empty or all values are filtered out.
  3. Improper Error Handling: The function lacks proper validation and doesn’t provide helpful error messages for invalid inputs.

Impact:
This bug leads to incorrect results in analytical operations where averages are used, potentially causing misleading outcomes in calculations and reports.

Expected Behavior:

  • Handle zero and negative numbers appropriately based on the use case (include or exclude).
  • Avoid division errors by validating the input list before calculations.
  • Provide meaningful error messages for invalid inputs.
@arjun-katonic-ai
Copy link
Author

QA:
The calculate_average() function produces incorrect results when processing lists with zero or negative numbers. For example:

Input:

calculate_average([5, 0, -3, 7])

Output:

Result: 2.25  # Includes negative and zero values incorrectly.

Additionally, the function crashes when the input list is empty:

calculate_average([])  # Raises ZeroDivisionError.

Can we update the function to handle these edge cases and provide appropriate error messages?

@arjun-katonic-ai
Copy link
Author

Developer:
Thanks for reporting this! I reviewed the calculate_average() function and found several issues:

  1. It doesn’t validate inputs, causing division errors with empty lists.
  2. There’s no option to exclude zero or negative values, which may not be valid for certain use cases.

I’ll refactor the function to:

  • Validate inputs and raise meaningful errors for empty or invalid lists.
  • Add an optional parameter to exclude zero and/or negative values from the calculation.

Working on the fix now.

@arjun-katonic-ai
Copy link
Author

Developer:
The function has been updated with the following improvements:

  1. Input Validation:

    • Checks if the input is a non-empty list.
    • Raises a ValueError with a clear message if validation fails.
  2. Enhanced Logic:

    • Added a filter_negative parameter to exclude negative values.
    • Added a filter_zero parameter to exclude zeros.
  3. Graceful Handling of Edge Cases:

    • Returns 0 if all values are filtered out.

Updated code snippet:

def calculate_average(numbers, filter_negative=False, filter_zero=False):
    if not numbers or not isinstance(numbers, list):
        raise ValueError("Input must be a non-empty list of numbers.")
    
    if filter_negative:
        numbers = [num for num in numbers if num >= 0]
    if filter_zero:
        numbers = [num for num in numbers if num != 0]
    
    if not numbers:
        return 0  # Gracefully handle cases where all numbers are filtered out.
    
    return sum(numbers) / len(numbers)

The changes are in branch fix/math-average-bug. Please validate with various test cases.

@arjun-katonic-ai
Copy link
Author

QA:
Tested the updated function with various scenarios:

  1. Default Behavior:

    • Input: [5, 0, -3, 7]
    • Output: 2.25 (all values included).
  2. Excluding Negatives:

    • Input: [5, 0, -3, 7], filter_negative=True
    • Output: 4.0 (excluded -3).
  3. Excluding Zeros:

    • Input: [5, 0, -3, 7], filter_zero=True
    • Output: 3.0 (excluded 0).
  4. Empty List:

    • Input: []
    • Output: ValueError: Input must be a non-empty list of numbers.
  5. All Numbers Filtered Out:

    • Input: [-3, -5], filter_negative=True
    • Output: 0.

Everything works perfectly. The function is now robust and flexible. Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant