Home > Backend Development > Python Tutorial > How to Create a Range with a Non-Integer Step in Python?

How to Create a Range with a Non-Integer Step in Python?

Mary-Kate Olsen
Release: 2024-12-11 15:35:11
Original
533 people have browsed it

How to Create a Range with a Non-Integer Step in Python?

How to Iterate through a Non-Integer Range

When attempting to create a range with a decimal step value using range(), you may encounter an error stating that the step argument cannot be zero. This arises because range() expects integer values for the start, stop, and step parameters.

Solution Using NumPy's linspace

To circumvent this issue and create a range with a non-integer step value, consider utilizing NumPy's linspace function. linspace takes the number of points to return and allows you to specify whether or not to include the right endpoint. For instance:

import numpy as np

# Create a range from 0 to 1 with 11 equally spaced points (including 1)
points = np.linspace(0, 1, 11)

# Create a range from 0 to 1 with 10 equally spaced points (excluding 1)
points_excl = np.linspace(0, 1, 10, endpoint=False)
Copy after login

Solution Using NumPy's arange

While using a floating-point step value is generally not recommended due to potential rounding errors, NumPy provides the arange function specifically designed for this purpose. However, be aware that rounding errors can still arise:

import numpy as np

# Create a range from 0.0 to 1.0 with a step value of 0.1
points = np.arange(0.0, 1.0, 0.1)

# Example of a potential rounding error using arange
points = np.arange(1, 1.3, 0.1)  # Expected length: 3, Actual length: 4
Copy after login

The above is the detailed content of How to Create a Range with a Non-Integer Step in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template