Skip to content

Fix: handle num=1 in RangeIndex.linspace to match numpy behavior#11403

Open
syu-toutousai wants to merge 1 commit into
pydata:mainfrom
syu-toutousai:fix/linspace-num1
Open

Fix: handle num=1 in RangeIndex.linspace to match numpy behavior#11403
syu-toutousai wants to merge 1 commit into
pydata:mainfrom
syu-toutousai:fix/linspace-num1

Conversation

@syu-toutousai

Copy link
Copy Markdown

Description

RangeIndex.linspace raises ZeroDivisionError when called with num=1 because it divides by (num - 1) when endpoint=True. numpy.linspace handles this case by returning a single-element array at the start value.

This fix adds an early return when num == 1, setting stop = start to produce a single-element RangeIndex, matching numpy's behavior.

Changes

  • xarray/indexes/range_index.py: Added num == 1 guard in linspace method

Testing

>>> RangeIndex.linspace(0, 1, num=1, dim="x")
# Before: ZeroDivisionError
# After: RangeIndex with start=0, stop=0, size=1

Fixes #11397


Payment: PayPal n6085530@gmail.com

When num=1, RangeIndex.linspace raised ZeroDivisionError because it
divided by (num - 1). NumPy's linspace returns a single-element array
at the start value in this case. This fix aligns the behavior.

Fixes pydata#11397
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

Successfully merging this pull request may close these issues.

Should RangeIndex.linspace handle num=1 like numpy.linspace?

1 participant