AppDividend
Latest Code Tutorials

# np logspace: Numpy.logspace() Function in Python

Numpy logspace() method is used to create an array of evenly spaced values between two numbers on the logarithmic scale.

## np logspace

The logspace() is a built-in numpy library function that returns number spaces evenly for intervals on a log scale. For example, the np.logspace() function returns a numpy array of uniformly spaced values on the log scale between the start and stop(including both).

### Syntax

``numpy.logspace(start, stop, num = 50, endpoint = True, base = 10.0, dtype = None)``

### Arguments

start: The base ** start is the starting value of the sequence.

stop: The base ** stop is the final value of the sequence unless the endpoint is False.

endpoint:  It is a boolean value, and if it is True, stop is the last sample. By default, True.

num: It is the number of samples to generate.

base: It is a Base of the log scale. By default, it equals 10.0.

dtype: It is the type of the output array.

### Return value

It returns a ndarray which is several samples equally spaced on a log scale.

### Example

Let’s take some examples of np.logspace() function with different arguments.

``````import numpy as np

# base = 2
print(np.logspace(1.0, 3.0, num=5, base=2))

# num = 5
print(np.logspace(2.0, 3.0, num=5))

# dtype = int
print(np.logspace(2.0, 5.0, num=5, dtype=int))``````

#### Output

``````[2. 2.82842712 4. 5.65685425 8. ]
[ 100. 177.827941 316.22776602 562.34132519 1000. ]
[ 100 562 3162 17782 100000]``````

To create an array of equally spaced numbers in Python, use the np.logspace() function.

``````import numpy as np

arr = np.logspace(1, 2, num=8)

print(arr)``````

#### Output

``[ 10. 13.89495494 19.30697729 26.82695795 37.2759372 51.79474679 71.9685673 100. ]``

## Using a different log base

By default, the base log is 10. The np.logspace() function uses 10 as the default base for the log scale. We can change the log bypassing the base argument.

``````import numpy as np

arr = np.logspace(1, 2, num=4, base=2)

print(arr)``````

#### Output

``[2. 2.5198421 3.1748021 4. ]``

Let’s visualize the even spaced values using the matplot library.

``````import numpy as np
import matplotlib.pyplot as plt

A = 20
a1 = np.logspace(0.4, 2, A, endpoint=True)
a2 = np.logspace(0.4, 2, A, endpoint=False)
b = np.zeros(A)
plt.plot(a1, b, 'o')
plt.ylim([-0.5, 2])
plt.show()``````

#### Output

You can see that the values grow wider apart as we move along the x-axis. This is because these values are equally spaced on the log scale and not the linear scale which we are viewing above.

Let’s convert these values with a log conversion and then plot them.

``````import numpy as np
import matplotlib.pyplot as plt

x = np.logspace(1, 2, num=8)
y = np.log10(x)
z = np.zeros(8)

plt.plot(y, z, 'o')
plt.show()``````

#### Output

That’s it for this tutorial.

This site uses Akismet to reduce spam. Learn how your comment data is processed.