To create a script in Python that generates n evenly spaced points on the surface of a sphere, we can use several techniques. One efficient method is to use the Fibonacci lattice, which provides a way to distribute points uniformly on the surface of a sphere.
Here's a Python script that demonstrates this, along with visualization using matplotlib.
Steps:
- Generate points on the sphere using the Fibonacci lattice method.
- Visualize the points using
matplotlib.
Here's the code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def fibonacci_sphere(samples=1000):
"""
Generates points on the surface of a sphere using the Fibonacci lattice method.
Args:
samples (int): The number of points to generate on the sphere.
Returns:
np.ndarray: An array of shape (samples, 3) containing the (x, y, z) coordinates of points on the sphere.
"""
points = []
phi = np.pi * (3. - np.sqrt(5.)) # golden angle in radians
for i in range(samples):
y = 1 - (i / float(samples - 1)) * 2 # y goes from 1 to -1
radius = np.sqrt(1 - y * y) # radius at y
theta = phi * i # golden angle increment
x = np.cos(theta) * radius
z = np.sin(theta) * radius
points.append((x, y, z))
return np.array(points)
def plot_sphere(points):
"""
Plots points on a sphere.
Args:
points (np.ndarray): The array of points to plot.
"""
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:, 0], points[:, 1], points[:, 2], s=20, color='b')
# Set the aspect ratio to be equal for all axes
ax.set_box_aspect([1, 1, 1])
# Set the limits to make the sphere visible
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
ax.set_zlim([-1, 1])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title(f'{len(points)} points on a sphere')
plt.show()
if __name__ == "__main__":
n = int(input("Enter the number of points to generate on the sphere: "))
points = fibonacci_sphere(samples=n)
plot_sphere(points)
Explanation:
fibonacci_sphere(samples): This function generates samples evenly distributed points on a unit sphere using the Fibonacci lattice technique. Each point's coordinates (x, y, z) are computed based on the golden angle.
plot_sphere(points): This function visualizes the generated points in a 3D scatter plot using matplotlib.
- The
if __name__ == "__main__" block accepts user input for the number of points and executes the functions to create and plot the points.
Usage:
- Make sure you have necessary libraries installed:
pip install numpy matplotlib
- Run the script and input the number of points when prompted. The visualization will appear in a window showing points distributed on the sphere.