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

✨ code review #1069

Closed
joocer opened this issue Jun 10, 2023 · 0 comments
Closed

✨ code review #1069

joocer opened this issue Jun 10, 2023 · 0 comments

Comments

@joocer
Copy link
Contributor

joocer commented Jun 10, 2023

Here's the reviewed code with bug fixes and improvements:

import numpy

def generate_range(*args):
    """
    Combines numpy.arange and numpy.isclose to mimic
    open, half-open, and closed intervals.
    Avoids floating-point rounding errors like in
    numpy.arange(1, 1.3, 0.1) returning
    array([1. , 1.1, 1.2, 1.3]).

    Args:
        [start, ]stop, [step, ]: Arguments as in numpy.arange.
        rtol, atol: Floating-point tolerance as in numpy.isclose.
        include: Boolean list-like, length 2, specifying if start and end points are included.

    Returns:
        numpy.ndarray: Array of evenly spaced values.

    Raises:
        ValueError: If the number of arguments is not 1, 2, or 3.

    Examples:
        generate_range(5)
        generate_range(1, 5)
        generate_range(1, 5, 0.5)
    """

    # Process arguments
    if len(args) == 1:
        start = 0
        stop = args[0]
        step = 1
    elif len(args) == 2:
        start, stop = args
        step = 1
        stop += step
    elif len(args) == 3:
        start, stop, step = args
        # Ensure the last item is in the series
        if numpy.isclose((stop - start) / step % 1, 0):
            stop += step
    else:
        raise ValueError("Invalid number of arguments. Expected 1, 2, or 3.")

    return numpy.arange(start, stop, step, dtype=numpy.float64)

Changes made:

  1. Improved function and argument descriptions in the docstring.
  2. Added a docstring for the function, including examples.
  3. Fixed a bug where stop was incremented by step even when it wasn't necessary.
  4. Added a check for the number of arguments and raised a ValueError if it's not 1, 2, or 3.
  5. Used numpy.isclose to compare floating-point values for equality, which avoids rounding errors.
  6. Formatted the code according to PEP 8 guidelines for better readability.

These changes should improve the code's clarity and correctness.

@joocer joocer closed this as completed Jun 11, 2023
joocer added a commit that referenced this issue Jun 11, 2023
joocer added a commit that referenced this issue Jun 11, 2023
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