xrange(start, stop, step)¶

An extended version of the python range function that accepts float arguments and creates a list of values.

The catch? Do simple plotting of functions without relying on numpy and linspace.


16.10.2025 Sverre Stikbakke

xrange.py¶

In [1]:
def xrange(start, stop, step):
    """
    xrange(start, stop, step) -> list object

    Parameters
    ----------
    start : float
        The first value
    stop : float
        The last value (included - different from range() function)
    step : float
        The interval between values

    Returns
    -------
    list
        A list with a sequence of float values

    Examples
    --------
    >>> xrange(-2, 2, 0.5)
    [-2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]
    """
    
    num_steps = int((stop - start) / step) + 1
    return [start + i * step for i in range(num_steps)]

usage, alt. 1¶

In [2]:
from xrange import xrange
import matplotlib.pyplot as plt


def f(x):
    y = 2*x**2 + 4*x + 3
    return y


x_values = xrange(-2, 2, 0.1)
y_values = [f(x) for x in x_values]

fig, ax = plt.subplots()

ax.plot(x_values, y_values)
ax.set_title('f(x) = 2*x^2 + 4*x + 3')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.grid(True)

plt.show()
No description has been provided for this image

usage, alt. 2¶

In [3]:
import matplotlib.pyplot as plt


def xrange(start, stop, step):
    num_steps = int((stop - start) / step) + 1
    return [start + i * step for i in range(num_steps)]


def f(x):
    y = 2*x**2 + 4*x + 3
    return y


x_values = xrange(-2, 2, 0.1)
y_values = [f(x) for x in x_values]

fig, ax = plt.subplots()

ax.plot(x_values, y_values)
ax.set_title('f(x) = 2*x^2 + 4*x + 3')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.grid(True)

plt.show()
No description has been provided for this image