Skip to content

RangeIndex.arange does not preserve step, has different values than numpy.arange #11325

@cfriedland5

Description

@cfriedland5

What happened?

When RangeIndex is constructed using arange it preserves stop, but since step is derived from (stop - start) / size step is not preserved and the index's values are inconsistent with numpy.arange.

To get the right values, the argument to stop should be adjusted so that both size and step are preserved. Alternatively, the underlying representation could be in terms of start, stop, and step directly.

What did you expect to happen?

The values materialized from a RangeIndex constructed with arange should have the provided step and match the values from numpy.arange.

Minimal Complete Verifiable Example

# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "xarray[complete]@git+https://github.com/pydata/xarray.git@main",
# ]
# ///
#
# This script automatically imports the development branch of xarray to check for issues.
# Please delete this header if you have _not_ tested this script with `uv run`!

import xarray as xr
xr.show_versions()
# your reproducer code ...
import numpy as np
from xarray.indexes import RangeIndex

start = 0.0
stop = 1.0
step = 0.3
print(f"Desired step: {step}")
print(f"numpy arange values: {np.arange(start, stop, step)}")
range_index = RangeIndex.arange(start, stop, step, dim="x")
print(f"RangeIndex step: {range_index.step}")
print(f"RangeIndex values: {np.asarray(range_index.to_pandas_index())}")
# Desired step: 0.3
# numpy arange values: [0.  0.3 0.6 0.9]
# RangeIndex step: 0.25
# RangeIndex values: [0.   0.25 0.5  0.75]

Steps to reproduce

No response

MVCE confirmation

  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.
  • Recent environment — the issue occurs with the latest version of xarray and its dependencies.

Relevant log output

Anything else we need to know?

No response

Environment

Details

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugneeds triageIssue that has not been reviewed by xarray team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions