Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open interval (a,b) and half-open interval (a,b] using Python's linspace

A half-open interval of the form [0,0.5) can be created using the following code:

rv = np.linspace(0., 0.5, nr, endpoint=False)

where nr is the number of points in the interval.

Question: How do I use linspace to create an open interval of the form (a,b) or a half-open interval of the form (a,b]?

like image 398
jonem Avatar asked Sep 07 '25 00:09

jonem


1 Answers

Probably the simplest way (since this functionality isn't built in to np.linspace()) is to just slice what you want. Let's say you're interested in the interval [0,1] with a spacing of 0.1.

>>> import numpy as np

>>> np.linspace(0, 1, 11)                     # [0,1]
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

>>> np.linspace(0, 1, 11-1, endpoint=False)   # [0,1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

>>> np.linspace(0, 1, 11)[:-1]                # [0,1) again
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

>>> np.linspace(0, 1, 11)[1:]                 # (0,1]
array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

>>> np.linspace(0, 1, 11)[1:-1]               # (0,1)
array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
like image 99
vanPelt2 Avatar answered Sep 08 '25 12:09

vanPelt2