Module 12 · Statistical Computing and Reproducibility Lesson 117 of 120

Vectorization, Index Alignment, and Shape Safety

Preventing a dimensionally valid but semantically wrong dot product.

2:27 clip6:17:13–6:19:41 in the full courseWatch on YouTube

Transcript

17 sentences · select one to jump there

Check your understanding

Why does the positional result pass a simple array-length check?

Choose one answer

Code lab

Run it yourself

The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.

117-vectorization-index-alignment-and-shape-safety.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 117 of 120
 * Vectorization, Index Alignment, and Shape Safety
 * Module 12: Statistical Computing and Reproducibility
 *
 * Scenario: Preventing a dimensionally valid but semantically wrong dot product
 * Rule:     align by identifier before multiplying vectors
 *
 * Try it:   Why does the positional result pass a simple array-length check?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/statistical-computing-and-reproducibility/vectorization-index-alignment-and-shape-safety/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson117() {
  const weights=[{id:"A",w:.4},{id:"B",w:.6}];
  const returns=[{id:"B",r:.02},{id:"A",r:.01}];
  const byId=new Map(returns.map(x=>[x.id,x.r]));
  const aligned=weights.reduce((s,x)=>{const r=byId.get(x.id);
    if(r===undefined) throw new Error("Missing asset");return s+x.w*r;},0);
  const positional=weights.reduce((s,x,i)=>s+x.w*returns[i].r,0);
  const result={aligned,positional};
  return result;
}

export const checkedResult = {"aligned":0.016,"positional":0.014};

// Run this file directly: npx tsx lessons/12-statistical-computing-and-reproducibility/117-vectorization-index-alignment-and-shape-safety.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson117(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "aligned": 0.016,
  "positional": 0.014
}

Prefer your own machine? Every file is in the course repository · open it in Codespaces.

Lesson notes

The rule

align by identifier before multiplying vectors