Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

NumPy Rounding and Trigonometric Functions

NumPy provides functions for rounding numerical values and performing trigonometric calculations on arrays. Rounding functions help control numerical precision, while trigonometric functions such as sine, cosine, and tangent are useful in geometry, physics, engineering, and scientific computing. In this lesson, you will learn the main functions, understand angle units, and apply these operations to practical examples.

1. Introduction to Rounding Functions

Rounding changes the precision or integer direction of a numerical value. NumPy provides functions to round to a specified number of decimal places, round down, round up, or remove the fractional portion.

Common Rounding Functions

  • np.round() rounds to the nearest value.
  • np.floor() rounds toward negative infinity.
  • np.ceil() rounds toward positive infinity.
  • np.trunc() removes the fractional part toward zero.
  • np.rint() rounds to the nearest integer-valued float, using ties-to-even.
import numpy as np values = np.array([2.3, 2.7, 3.5, -2.3, -2.7]) print("Round:", np.round(values)) print("Floor:", np.floor(values)) print("Ceiling:", np.ceil(values)) print("Truncate:", np.trunc(values))

Output:

Round: [ 2. 3. 4. -2. -3.] Floor: [ 2. 2. 3. -3. -3.] Ceiling: [ 3. 3. 4. -2. -2.] Truncate: [ 2. 2. 3. -2. -2.]

2. Rounding to Decimal Places

The np.round() function accepts an array and an optional number of decimal places. A positive value rounds to decimal places, while a negative value rounds to positions to the left of the decimal point.

import numpy as np prices = np.array([12.3456, 45.6789, 98.7654]) print("Two decimal places:", np.round(prices, 2)) print("One decimal place:", np.round(prices, 1)) print("Nearest integer:", np.round(prices))

Output:

Two decimal places: [12.35 45.68 98.77] One decimal place: [12.3 45.7 98.8] Nearest integer: [12. 46. 99.]

Rounding to Tens and Hundreds

import numpy as np values = np.array([123, 267, 349, 851]) print("Nearest ten:", np.round(values, -1)) print("Nearest hundred:", np.round(values, -2))

Output:

Nearest ten: [120 270 350 850] Nearest hundred: [100 300 300 900]
Tip: Negative decimal-place values are useful for rounding amounts to tens, hundreds, or larger place values.

3. Understanding Floor, Ceiling, and Truncation

These functions can produce different results for negative values. Understanding their direction is important when working with financial calculations, measurements, and numerical data.

Function Behavior Example for -3.7
np.floor() Moves toward negative infinity. -4.0
np.ceil() Moves toward positive infinity. -3.0
np.trunc() Moves toward zero. -3.0
np.round() Rounds to the nearest value, with ties-to-even for exact halfway cases. -4.0
Rounding -3.7 Floor -4 Toward -∞ Ceiling -3 Toward +∞ Truncate -3 Toward zero Round -4 Nearest integer The rounding direction determines the result.

Negative values make the difference between floor and truncation easy to see.

4. Introduction to Trigonometric Functions

Trigonometric functions describe relationships between angles and sides of triangles. NumPy provides vectorized functions that calculate these values for individual numbers or entire arrays.

Function Description
np.sin() Calculates the sine of each angle.
np.cos() Calculates the cosine of each angle.
np.tan() Calculates the tangent of each angle.
np.arcsin() Calculates the inverse sine.
np.arccos() Calculates the inverse cosine.
np.arctan() Calculates the inverse tangent.
Important: NumPy's trigonometric functions use radians, not degrees. Convert degree values to radians before passing them to np.sin(), np.cos(), or np.tan().

5. Converting Degrees to Radians

Degrees and radians are two units for measuring angles. A full circle contains 360 degrees or \(2\pi\) radians. NumPy provides np.deg2rad() and np.radians() for converting degrees into radians.

import numpy as np degrees = np.array([0, 30, 45, 60, 90, 180]) radians = np.deg2rad(degrees) print("Degrees:", degrees) print("Radians:", np.round(radians, 4))

Output:

Degrees: [ 0 30 45 60 90 180] Radians: [0. 0.5236 0.7854 1.0472 1.5708 3.1416]

Convert Radians Back to Degrees

import numpy as np radians = np.array([0, np.pi / 4, np.pi / 2, np.pi]) degrees = np.rad2deg(radians) print(degrees)

Output:

[ 0. 45. 90. 180.]
Remember: Use np.deg2rad() when your input angles are in degrees and use np.rad2deg() when converting radian results to degrees.

6. Sine, Cosine, and Tangent

The sine, cosine, and tangent functions can be applied directly to arrays of angles expressed in radians.

import numpy as np degrees = np.array([0, 30, 45, 60, 90]) radians = np.deg2rad(degrees) print("Sine:", np.round(np.sin(radians), 4)) print("Cosine:", np.round(np.cos(radians), 4)) print("Tangent:", np.round(np.tan(radians), 4))

Output:

Sine: [0. 0.5 0.7071 0.866 1. ] Cosine: [1. 0.866 0.7071 0.5 0. ] Tangent: [0. 0.5774 1. 1.7321 1.6331e+16]

The tangent of 90 degrees is mathematically undefined. Because computers use floating-point approximations, NumPy may return a very large finite number instead of infinity for this input.

Trigonometric Values at Common Angles Angle 0° 30° 45° 60° sin 0 0.5 0.7071 0.8660 cos 1 0.8660 0.7071 0.5 tan 0 0.5774 1 1.7321

Values shown are rounded approximations of common trigonometric results.

7. Inverse Trigonometric Functions

Inverse trigonometric functions calculate an angle from a trigonometric ratio. Their results are expressed in radians.

import numpy as np values = np.array([0, 0.5, 1.0]) print("Arcsine:", np.round(np.arcsin(values), 4)) print("Arccosine:", np.round(np.arccos(values), 4)) print("Arctangent:", np.round(np.arctan(values), 4))

Output:

Arcsine: [0. 0.5236 1.5708] Arccosine: [1.5708 1.0472 0. ] Arctangent: [0. 0.4636 0.7854]

Converting an Inverse Result to Degrees

import numpy as np ratio = np.array([0, 0.5, 1.0]) angles = np.rad2deg(np.arctan(ratio)) print(np.round(angles, 2))

Output:

[ 0. 26.57 45. ]
Important: The real-valued input domain of np.arcsin() and np.arccos() is from -1 to 1. Values outside this interval produce NaN results for real-valued calculations.

8. Hyperbolic Functions

NumPy also provides hyperbolic functions. These are related to exponential functions and are used in mathematical models, physics, engineering, and machine learning.

Function Description
np.sinh() Hyperbolic sine.
np.cosh() Hyperbolic cosine.
np.tanh() Hyperbolic tangent.
import numpy as np values = np.array([-2, -1, 0, 1, 2]) print("Sinh:", np.round(np.sinh(values), 3)) print("Cosh:", np.round(np.cosh(values), 3)) print("Tanh:", np.round(np.tanh(values), 3))

Output:

Sinh: [-3.627 -1.175 0. 1.175 3.627] Cosh: [3.762 1.543 1. 1.543 3.762] Tanh: [-0.964 -0.762 0. 0.762 0.964]

9. Practical Project: Angle Calculations

In this project, we will convert a collection of angles from degrees to radians and calculate their sine and cosine values.

import numpy as np angles_degrees = np.array([0, 30, 45, 60, 90, 180]) angles_radians = np.deg2rad(angles_degrees) sine_values = np.sin(angles_radians) cosine_values = np.cos(angles_radians) print("Angle | Sine | Cosine") for degree, sine, cosine in zip( angles_degrees, sine_values, cosine_values ): print( f"{degree:5} | {sine:7.4f} | {cosine:7.4f}" )

Output:

Angle | Sine | Cosine 0 | 0.0000 | 1.0000 30 | 0.5000 | 0.8660 45 | 0.7071 | 0.7071 60 | 0.8660 | 0.5000 90 | 1.0000 | 0.0000 180 | 0.0000 | -1.0000

The calculations are performed using NumPy arrays. The loop formats the results into readable rows for display.

10. Practical Project: Rounding Measurements

Scientific measurements often contain more decimal places than are needed in a report. Rounding can make results easier to read while retaining the original values for further calculations.

import numpy as np measurements = np.array([12.3478, 18.9264, 25.5555, 31.1249]) rounded_measurements = np.round(measurements, 2) floored_measurements = np.floor(measurements) ceiling_measurements = np.ceil(measurements) print("Original:", measurements) print("Rounded:", rounded_measurements) print("Floor:", floored_measurements) print("Ceiling:", ceiling_measurements)

Output:

Original: [12.3478 18.9264 25.5555 31.1249] Rounded: [12.35 18.93 25.56 31.12] Floor: [12. 18. 25. 31.] Ceiling: [13. 19. 26. 32.]
Best practice: Keep the original measurement array when you need full precision later. Use a rounded copy for reporting or display purposes.

11. Common Mistakes and Best Practices

Passing Degrees Directly to Trigonometric Functions

NumPy expects radians. Convert degree values using np.deg2rad() before calculating sine, cosine, or tangent.

Assuming Rounding Always Goes Up

np.round() rounds to the nearest value and uses ties-to-even for exact halfway cases. Use np.ceil() when you specifically need rounding toward positive infinity.

Confusing Floor and Truncation

Floor moves toward negative infinity, while truncation moves toward zero. Their results can differ for negative decimal values.

Ignoring Floating-Point Precision

Results such as cosine of 90 degrees may be extremely close to zero rather than exactly zero. Round for presentation when appropriate.

Using Inverse Functions Outside Their Domain

Real-valued arcsine and arccosine accept inputs between -1 and 1. Validate values before applying these functions.

12. Practice Exercises

Exercise 1: Decimal Rounding

Create an array of decimal values. Round each value to two decimal places using np.round().

Exercise 2: Negative Rounding

Apply np.floor(), np.ceil(), and np.trunc() to an array containing positive and negative decimal values. Compare the results.

Exercise 3: Degree Conversion

Convert 0, 45, 90, 135, and 180 degrees into radians using np.deg2rad().

Exercise 4: Trigonometric Calculations

Calculate sine, cosine, and tangent for 0, 30, 45, and 60 degrees. Display the results rounded to four decimal places.

Exercise 5: Inverse Trigonometry

Calculate the inverse sine and inverse cosine for [0, 0.5, 1]. Convert the results into degrees.

Exercise 6: Measurement Processing

Create an array of measurement values and produce rounded, floor, and ceiling results without changing the original array.

Summary

In this lesson, you learned to round numerical arrays using np.round(), np.floor(), np.ceil(), and np.trunc(). You also practiced controlling decimal precision and rounding values to tens and hundreds.

You explored trigonometric functions such as np.sin(), np.cos(), and np.tan(), along with inverse and hyperbolic functions. You also learned to convert angles between degrees and radians and apply these functions to practical numerical calculations.