5.4.2Scientific Computing (Python)

Array creation — np.zeros, np.ones, np.linspace, np.arange, np.random

1,775 words8 min readdifficulty · medium

WHY do we need dedicated creators?

A Python list [0]*1000000 is slow and memory-heavy: each element is a full Python object with a pointer. NumPy instead allocates one typed buffer. So np.zeros(10**6) is fast, compact, and ready for vectorized math. The creators also let you preallocate an output and fill it — the standard fast pattern in scientific code.


np.zeros and np.ones

WHAT they give: a fully-initialized array. HOW they work: allocate buffer → set every byte (zeros literally memset to 0; ones writes the value 1 in the chosen dtype). WHY the default dtype is float64: scientific math wants floats; pass dtype=int if you need integers.

Related: np.full(shape, 7) → filled with 7; np.empty(shape)uninitialized (garbage values, fastest, only safe if you overwrite everything).


np.linspace — N points, endpoints included

Derivation of the spacing (from scratch)

We want num points x0,,xnum1x_0,\dots,x_{num-1} with x0=ax_0=a, xnum1=bx_{num-1}=b, equally spaced. There are num1num-1 gaps between numnum points. So each gap is

Δ=banum1,xk=a+kΔ,k=0,1,,num1.\Delta = \frac{b-a}{num-1}, \qquad x_k = a + k\,\Delta,\quad k=0,1,\dots,num-1.


np.arange — fixed step, like range

Derivation of the count

Values are a,a+s,a+2s,a, a+s, a+2s,\dots stopping before bb. The number of elements is

N=bas.N = \left\lceil \frac{b-a}{s} \right\rceil.


np.random — random arrays

WHY a seed? Reproducible experiments: same seed → same numbers, so a teammate (or your future self) gets identical output.

The mean of rng.random() samples → 0.50.5 (uniform on [0,1)[0,1) has mean 12\tfrac12). The mean of rng.normal(loc, scale, ...)loc, std → scale, for large samples.


Figure — Array creation — np.zeros, np.ones, np.linspace, np.arange, np.random

Recall Feynman: explain to a 12-year-old

Imagine an empty egg carton. np.zeros is a carton where every cup holds a "0" egg; np.ones holds "1" eggs. np.linspace is like saying "I want exactly 5 marks painted evenly on a ruler from 0 to 1, including the very ends." np.arange is "start walking from 0 and take 0.25-size steps, stop before you reach 1." np.random is rolling dice to fill the cups with surprise numbers — and a seed is a magic word that makes the dice always land the same way so you can replay the game.


Common mistakes (steel-manned)


Flashcards

What does np.zeros((2,3)) return?
A 2×3 float array of zeros (shape passed as a tuple).
Default dtype of np.zeros / np.ones?
float64.
Spacing formula for np.linspace(a,b,num) with endpoint=True?
Δ=(ba)/(num1)\Delta=(b-a)/(num-1).
Does np.linspace include the stop by default?
Yes (endpoint=True).
Does np.arange include the stop value?
No, stop is exclusive (like Python range).
Number of elements in np.arange(a,b,s)?
(ba)/s\lceil (b-a)/s \rceil.
Why avoid float steps in np.arange?
Floating-point rounding makes the count/last value unreliable; use linspace.
How many points and what step does np.linspace(0,1,5) give?
5 points, step 0.25 → [0,0.25,0.5,0.75,1].
What does np.empty give that np.zeros doesn't?
Uninitialized (garbage) values — faster, only safe if you overwrite all.
Modern way to make a random generator?
rng = np.random.default_rng(seed).
Why pass a seed to the RNG?
Reproducibility — same seed yields the same sequence.
rng.random((2,2)) range?
Uniform floats in [0,1).
Expected mean of many rng.random() samples?
0.5.
How to make a 4×4 array all equal to 7?
np.full((4,4), 7).

Connections

  • NumPy arrays — shape, dtype, ndim
  • Vectorization vs Python loops
  • Array indexing and slicing
  • Reshaping — reshape, ravel, newaxis
  • Plotting functions with Matplotlib (linspace feeds the x-axis)
  • Random sampling and distributions
  • Floating-point representation and rounding errors

Concept Map

why

too slow, motivates

blank slate

blank slate

even samples

stepped range

randomness

uses

uses

enables

derived from

Need typed number container

Python list is slow and heavy

NumPy array: one typed buffer + shape

np.zeros -> filled 0

np.ones -> filled 1

np.linspace: N points, ends included

np.arange: fixed step, stop excluded

np.random: random numbers

dtype default float64

Preallocate then fill pattern

gap = b-a / num-1

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, scientific computing me sabse pehla kaam hota hai numbers ka ek container banana — yahi NumPy array hai: ek hi dtype ka contiguous memory block jiska ek shape hota hai. np.zeros aur np.ones ka kaam simple hai: ek khaali slate de do, sab 0 ya sab 1 se bhara hua. Yaad rakho shape tuple me jaata hai, jaise np.zeros((3,4)) — agar comma se do number diye np.zeros(3,4) to error, kyunki doosra slot dtype ka hai.

np.linspace aur np.arange ka fark exam-favorite hai. linspace(a, b, num) bolta hai "mujhe interval [a,b][a,b] me exactly num points chahiye, dono ends include karke" — step khud calculate hota hai: Δ=(ba)/(num1)\Delta=(b-a)/(num-1), kyunki num points ke beech num-1 gaps hote hain (fencepost logic). arange(a, b, s) Python ke range jaisa hai: fixed step s se chalo, par b ko chhod do (exclusive). Plotting ke liye hamesha linspace use karo, aur float steps wale arange se bacho kyunki 0.1 exact store nahi hota, isliye last value aur count kabhi-kabhi galat aa jaata hai.

np.random me modern tareeka hai rng = np.random.default_rng(seed). rng.random() deta hai [0,1)[0,1) uniform, rng.normal(mean, std, size) deta hai Gaussian. Seed ka magic ye hai ki same seed → same numbers, to tumhara experiment reproducible ban jaata hai — teammate ko bilkul wahi output milega. Bottom line: blank chahiye to zeros/ones, kitne points chahiye to linspace, kitna bada step chahiye to arange, aur randomness chahiye to random. Itna clear ho gaya to ye topic 80/20 me tumhare paas pakka hai.

Go deeper — visual, from zero

Test yourself — Scientific Computing (Python)

Connections