Skip to content

[Edit] - numpy linspace() #6721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 133 additions & 43 deletions content/numpy/concepts/built-in-functions/terms/linspace/linspace.md
Original file line number Diff line number Diff line change
@@ -1,87 +1,177 @@
---
Title: '.linspace()'
Description: 'Returns an array of evenly-spaced numbers over a given interval.'
Description: 'Creates an array of evenly spaced numbers over a specified interval.'
Subjects:
- 'Computer Science'
- 'Data Science'
- 'Web Development'
Tags:
- 'Data Structures'
- 'Arrays'
- 'Functions'
- 'Data Structures'
- 'NumPy'
- 'Python'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
---

The **`.linspace()`** function returns an array of evenly-spaced numbers over a specified interval \[`start`,`stop`\], optionally excluding the `stop` value.
The **`.linspace()`** function in NumPy creates an array of evenly spaced numbers over a specified interval. Unlike other sequence-generating functions such as `.arange()`, `.linspace()` allows specifying the exact number of points needed in the array, and NumPy will automatically calculate the spacing between the values. This makes it particularly useful for generating sample points for mathematical functions, creating coordinate grids for plotting, and designing evenly spaced numerical sequences for scientific computing.

The function is commonly used in data visualization, signal processing, numerical integration, and mathematical modeling where precise control over the number of samples in an interval is needed. It's especially valuable when working with functions that need to be evaluated at regular intervals, or when creating axes for plots that require specific numbers of data points.

## Syntax

```pseudo
numpy.linspace(start, stop, num, endpoint, retstep, dtype, axis)
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
```

The `start` and `stop` arguments are required and represent the beginning and end of the interval. They can be numbers or arrays.
**Parameters:**

`.linspace()` provides the following arguments:
- `start`: The starting value of the sequence.
- `stop`: The end value of the sequence.
- `num` (optional): Number of samples to generate. Default is `50`.
- `endpoint` (optional): If `True` (default), stop is the last sample. Otherwise, it is not included.
- `retstep` (optional): If `True`, returns (samples, step), where step is the spacing between samples.
- `dtype` (optional): The type of the output array. If not given, the data type is inferred from start and stop.
- `axis` (optional): The axis in the result to store the samples. Relevant only if start or stop are array-like.

- `start`: The starting point of the sequence.
- `stop`: The (optionally included) endpoint of the sequence.
- `num`: The number of values to generate. Defaults to 50.
- `endpoint`: Boolean flag. If `True`, `stop` is included as the last value. If `False`, `stop` is excluded. Defaults to `True`.
- `retstep`: Boolean flag. If `True`, the result will include the calculated step size between values. Defaults to `False`.
- `dtype`: The `dtype` of the returned array, if omitted, `dtype` is inferred from `start` and `stop`. Defaults to `None`.
- `axis`: If `start` and `stop` are arrays, this specifies on what axis the values will be added. If `0` the axis is added at the beginning. If `-1`, it's added at the end. Defaults to `0`.
**Return value:**

## Example
- Returns a numpy [ndarray](https://www.codecademy.com/resources/docs/numpy/ndarray1) of evenly spaced samples. If retstep is True, it also returns the step size between samples.

The following example creates a list of values between 10 and 20.
## Example 1: Basic Usage of `.linspace()`

This example shows how to create a simple array of evenly spaced numbers using the `.linspace()` function:

```py
import numpy
import numpy as np

result = numpy.linspace(10, 20, num=6)
print(result)
# Create an array of 5 values evenly spaced from 0 to 1
array = np.linspace(0, 1, 5)

result2 = numpy.linspace(10, 20, num=6, endpoint=False)
print(result2)
# Print the array
print("Evenly spaced array:")
print(array)

result3 = numpy.linspace([1,2,3],[4,5,6], num=6)
print(result3)
# Calculate the step size manually to verify
step_size = (1 - 0) / (5 - 1)
print(f"Manually calculated step size: {step_size}")

# Alternatively, get the step size directly using retstep
array, step = np.linspace(0, 1, 5, retstep=True)
print(f"Step size returned by linspace: {step}")
```

This results in the following output:
The output generated by this code will be:

```shell
[10. 12. 14. 16. 18. 20.]
Evenly spaced array:
[0. 0.25 0.5 0.75 1. ]
Manually calculated step size: 0.25
Step size returned by linspace: 0.25
```

This example demonstrates how to create an array of 5 evenly spaced values from 0 to 1. The step size is 0.25, which we verify both by manual calculation and by using the `retstep` parameter.

## Example 2: Plotting a Sine Wave using `.linspace()`

[10. 11.66666667 13.33333333 15. 16.66666667 18.33333333]
This example demonstrates how to use `.linspace()` to create x-coordinates for plotting a sine wave:

[[1. 2. 3. ]
[1.6 2.6 3.6]
[2.2 3.2 4.2]
[2.8 3.8 4.8]
[3.4 4.4 5.4]
[4. 5. 6. ]]
```py
import numpy as np
import matplotlib.pyplot as plt

# Create x values from 0 to 2π with 100 points
x = np.linspace(0, 2 * np.pi, 100)

# Calculate sine values for each x
y = np.sin(x)

# Plot the sine wave
plt.figure(figsize=(10, 5))
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
plt.axvline(x=0, color='k', linestyle='-', alpha=0.3)

# Show the plot
plt.show()

# Print a few sample points to illustrate the even spacing
print("First 5 x values:", x[:5])
print("Corresponding y values:", y[:5])
```

Output of this code will be:

![A sinewave created using the `.linspace()` function](https://raw.githubusercontent.com/Codecademy/docs/main/media/sine-wave-using-linspace.png)

```shell
First 5 x values: [0. 0.06346652 0.12693304 0.19039955 0.25386607]
Corresponding y values: [0. 0.06342392 0.12655467 0.18930021 0.25157326]
```

## Codebyte Example
This example shows how linspace() is used in data visualization to create evenly spaced points for plotting a mathematical function. The x-axis values are generated with linspace() to ensure an even distribution of points over the domain, which results in a smooth curve.

## Codebyte Example: Creating a Temperature Gradient Simulation

Run the following codebyte example to understand the usage of the `linspace()` function with different inputs and parameters:
This example demonstrates how to use `.linspace()` for a practical application - simulating temperature distribution along a metal rod:

```codebyte/python
import numpy as np

result, step_size = np.linspace(0, 20, num=5, retstep=True)
print("Resulting array: ", result)
print("Step size: ", step_size)
# Parameters
rod_length = 100 # cm
num_points = 50 # number of measurement points
temp_left = 100 # temperature at left end (°C)
temp_right = 30 # temperature at right end (°C)

result2, step_size2 = np.linspace(0, 20, num=5, endpoint=False, retstep=True)
print("Resulting array (without endpoint): ", result2)
print("Step size: ", step_size2)
# Create positions along the rod using linspace
positions = np.linspace(0, rod_length, num_points)

result3 = np.linspace([0, 10], [20, 100], num=8, axis=1)
print(result3)
# Create temperature distribution (linear for this simple model)
temperatures = np.linspace(temp_left, temp_right, num_points)

# Add some random noise to simulate measurement errors
np.random.seed(42) # for reproducibility
noise = np.random.normal(0, 2, num_points) # mean 0, std dev 2
temperatures_with_noise = temperatures + noise

# Print some sample data points
print("Position (cm) | Ideal Temp (°C) | Measured Temp (°C)")
print("-" * 50)
for i in range(0, num_points, 10): # Print every 10th point
print(f"{positions[i]:11.2f} | {temperatures[i]:13.2f} | {temperatures_with_noise[i]:16.2f}")
```

This example illustrates a practical application of `.linspace()` in scientific modeling. We create evenly spaced measurement points along a rod and model a linear temperature gradient. The use of `.linspace()` ensures that our measurement points are uniformly distributed, which is crucial for accurate simulation and visualization of physical phenomena.

## Frequently Asked Questions

### 1. What's the difference between `np.linspace()` and `np.arange()`?

While both functions create sequences of numbers, `np.linspace()` lets you specify the number of points and generates evenly spaced values, whereas `np.arange()` requires a step size. `.linspace()` is generally preferred for floating-point ranges as it avoids rounding errors that can accumulate when using `.arange()` with decimal steps.

### 2. What is the difference between NumPy `.linspace()` and `.logspace()`?

NumPy `.linspace()` creates values evenly spaced on a linear scale, while `.logspace()` creates values evenly spaced on a logarithmic scale. `.logspace()` generates points between 10^start and 10^stop, making it ideal for data spanning multiple orders of magnitude or for logarithmic plots.

### 3. Can `.linspace()` generate logarithmic sequences?

No, `.linspace()` generates linearly spaced sequences. For logarithmic sequences, use `np.logspace()` which creates numbers evenly spaced on a log scale.

### 4. How do I exclude the endpoint in `.linspace()`?

Set the endpoint parameter to False: `np.linspace(start, stop, num, endpoint=False)`

### 5. Is there a multidimensional version of `.linspace()`?

Yes, you can create multidimensional arrays by reshaping the output or using meshgrid with linspace. For example:

```py
x = np.linspace(0, 1, 10)
y = np.linspace(0, 1, 10)
X, Y = np.meshgrid(x, y) # Creates a 2D grid
```
Binary file added media/sine-wave-using-linspace.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.