Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

47. Sin and cosine feature encoding

easy
GeneralGeneral
senior

Sinusoidal encoding turns a cyclic feature (like hour-of-day) into two smooth features using sine and cosine so models don’t treat the “end” and “start” as far apart. You’ll implement this encoding for an array of cyclic values and return the encoded features as NumPy arrays.

sin=sin(2πxp),cos=cos(2πxp)\text{sin} = \sin\left(2\pi \frac{x}{p}\right), \quad \text{cos} = \cos\left(2\pi \frac{x}{p}\right)

Requirements

Implement the function

python

Rules:

  • Use the formula above to compute one sine and one cosine value per input.
  • Return a tuple of two NumPy arrays: all sine values, then all cosine values.
  • Use NumPy for vectorized math (np.sin, np.cos, np.pi).
  • Do not use any feature-engineering helper libraries (e.g., sklearn encoders).

Example

python

Output:

python
Input Signature
ArgumentType
periodfloat
valuesnp.ndarray
Output Signature
Return NameType
valuetuple

Constraints

  • Use NumPy sin/cos; return NumPy arrays.

  • No sklearn/feature-engineering helper libraries.

  • Output tuple of np.ndarrays: (sin_arr, cos_arr).

Hint 1

Map each value onto the unit circle by converting it to an angle in radians: angle = 2π * x / period.

Hint 2

Use NumPy element-wise operations to compute angle, sin(angle), and cos(angle) for the entire array at once.

Hint 3

Use np.pi for π, and ensure your input is treated as a NumPy array (which it is). Return np.sin(angles), np.cos(angles).

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
cyclical-features
sinusoidal-encoding
numpy-vectorization
feature-engineering
46 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit