Sobes.tech
Junior — Middle

How can you check if a point is inside a sphere or a cube based on its coordinates?

sobes.tech AI

Answer from AI

To check whether a point is inside a sphere or a cube, you need to compare the point's coordinates with the parameters of these shapes.

For a sphere:

  • Let the sphere's center be (cx, cy, cz), and its radius be r.
  • The point is (x, y, z).
  • Calculate the distance from the point to the center: d = sqrt((x - cx)² + (y - cy)² + (z - cz)²).
  • If d ≤ r, the point is inside the sphere.

For an axis-aligned cube:

  • Let the cube be defined by two opposite corners: min_corner = (xmin, ymin, zmin), max_corner = (xmax, ymax, zmax).
  • The point is inside the cube if the following conditions are all true: xmin ≤ x ≤ xmax, ymin ≤ y ≤ ymax, zmin ≤ z ≤ zmax.

Example in Python:

import math

def is_point_in_sphere(point, center, radius):
    x, y, z = point
    cx, cy, cz = center
    distance = math.sqrt((x - cx)**2 + (y - cy)**2 + (z - cz)**2)
    return distance <= radius

def is_point_in_cube(point, min_corner, max_corner):
    x, y, z = point
    xmin, ymin, zmin = min_corner
    xmax, ymax, zmax = max_corner
    return xmin <= x <= xmax and ymin <= y <= ymax and zmin <= z <= zmax

# Example usage
point = (1, 2, 3)
sphere_center = (0, 0, 0)
sphere_radius = 5
cube_min = (0, 0, 0)
cube_max = (3, 3, 3)

print(is_point_in_sphere(point, sphere_center, sphere_radius))  # True
print(is_point_in_cube(point, cube_min, cube_max))            # False