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.
Transcript
17 sentences · select one to jump thereCheck your understanding
Why does the positional result pass a simple array-length check?
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.
/**
* 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
}# 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.
#
# Run: python main.py
import json
def lesson_117():
weights = [{"id": "A", "w": 0.4}, {"id": "B", "w": 0.6}]
returns = [{"id": "B", "r": 0.02}, {"id": "A", "r": 0.01}]
by_id = {x["id"]: x["r"] for x in returns}
aligned = 0.0
for x in weights:
if x["id"] not in by_id:
raise KeyError("Missing asset")
aligned += x["w"] * by_id[x["id"]]
positional = 0.0
for i, x in enumerate(weights):
positional += x["w"] * returns[i]["r"]
return {"aligned": aligned, "positional": positional}
if __name__ == "__main__":
print(json.dumps(lesson_117(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"aligned": 0.016,
"positional": 0.014
}/*
* 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.
*
* Run: javac Main.java && java Main
*/
import java.util.*;
public class Main {
static Map<String, Object> lesson117() {
String[] weightIds = {"A", "B"};
double[] weights = {.4, .6};
String[] returnIds = {"B", "A"};
double[] returns = {.02, .01};
Map<String, Double> byId = new HashMap<String, Double>();
for (int i = 0; i < returnIds.length; i++) byId.put(returnIds[i], returns[i]);
double aligned = 0;
for (int i = 0; i < weightIds.length; i++) {
Double r = byId.get(weightIds[i]);
if (r == null) throw new IllegalStateException("Missing asset");
aligned += weights[i] * r;
}
double positional = 0;
for (int i = 0; i < weights.length; i++) positional += weights[i] * returns[i];
return obj("aligned", aligned, "positional", positional);
}
public static void main(String[] args) {
System.out.println(toJson(lesson117(), ""));
}
// Minimal JSON writer: insertion-ordered Map, List, Number, Boolean, String and null.
static String toJson(Object value, String indent) {
if (value == null) return "null";
if (value instanceof String) return quote((String) value);
if (value instanceof Boolean) return value.toString();
if (value instanceof Double) return formatNumber((Double) value);
if (value instanceof Number) return value.toString();
String inner = indent + " ";
StringBuilder sb = new StringBuilder();
if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
if (map.isEmpty()) return "{}";
sb.append("{\n");
int i = 0;
for (Map.Entry<?, ?> e : map.entrySet()) {
sb.append(inner).append(quote(e.getKey().toString())).append(": ").append(toJson(e.getValue(), inner));
sb.append(++i < map.size() ? ",\n" : "\n");
}
return sb.append(indent).append("}").toString();
}
List<?> list = (List<?>) value;
if (list.isEmpty()) return "[]";
sb.append("[\n");
for (int i = 0; i < list.size(); i++) {
sb.append(inner).append(toJson(list.get(i), inner)).append(i + 1 < list.size() ? ",\n" : "\n");
}
return sb.append(indent).append("]").toString();
}
// Integral doubles print without ".0", as JavaScript does; others use Java's round-trip form.
static String formatNumber(double x) {
if (x == Math.rint(x) && Math.abs(x) < 1e15) return Long.toString((long) x);
return Double.toString(x);
}
static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') sb.append('\\').append(c);
else if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
return sb.append('"').toString();
}
// Builds an insertion-ordered object from alternating keys and values.
static Map<String, Object> obj(Object... keysAndValues) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (int i = 0; i < keysAndValues.length; i += 2) map.put((String) keysAndValues[i], keysAndValues[i + 1]);
return map;
}
static List<Object> list(double... values) {
List<Object> out = new ArrayList<Object>();
for (double v : values) out.add(v);
return out;
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"aligned": 0.016,
"positional": 0.014
}// 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.
//
// Run: go run main.go
package main
import (
"encoding/json"
"fmt"
)
type Result struct {
Aligned float64 `json:"aligned"`
Positional float64 `json:"positional"`
}
type weight struct {
id string
w float64
}
type assetReturn struct {
id string
r float64
}
func lesson117() Result {
weights := []weight{{"A", .4}, {"B", .6}}
returns := []assetReturn{{"B", .02}, {"A", .01}}
byID := map[string]float64{}
for _, x := range returns {
byID[x.id] = x.r
}
aligned := 0.0
for _, x := range weights {
r, ok := byID[x.id]
if !ok {
panic("Missing asset")
}
aligned += x.w * r
}
positional := 0.0
for i, x := range weights {
positional += x.w * returns[i].r
}
return Result{Aligned: aligned, Positional: positional}
}
func main() {
out, err := json.MarshalIndent(lesson117(), "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"aligned": 0.016,
"positional": 0.014
}// 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.
//
// Run: g++ -std=c++17 -O1 -o lesson main.cpp && ./lesson
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#include <vector>
// Minimal JSON value: objects keep insertion order; numbers print in shortest round-trip form.
struct Json {
enum class Kind { Null, Bool, Number, String, Array, Object };
Kind kind = Kind::Null;
bool flag = false;
double number = 0.0;
std::string text;
std::vector<std::string> keys; // object keys, parallel to items
std::vector<Json> items; // array items, or object values
};
Json jnull() { return Json{}; }
Json jbool(bool value) { Json j; j.kind = Json::Kind::Bool; j.flag = value; return j; }
Json jnum(double value) { Json j; j.kind = Json::Kind::Number; j.number = value; return j; }
Json jstr(const std::string& value) { Json j; j.kind = Json::Kind::String; j.text = value; return j; }
Json jarr(std::vector<Json> items) { Json j; j.kind = Json::Kind::Array; j.items = std::move(items); return j; }
Json jobj(std::vector<std::pair<std::string, Json>> fields) {
Json j;
j.kind = Json::Kind::Object;
for (auto& field : fields) {
j.keys.push_back(field.first);
j.items.push_back(std::move(field.second));
}
return j;
}
Json jnums(const std::vector<double>& values) {
std::vector<Json> items;
for (double v : values) items.push_back(jnum(v));
return jarr(std::move(items));
}
Json jnums(const std::vector<std::optional<double>>& values) {
std::vector<Json> items;
for (const auto& v : values) items.push_back(v ? jnum(*v) : jnull());
return jarr(std::move(items));
}
std::string formatNumber(double value) {
char buffer[64];
auto result = std::to_chars(buffer, buffer + sizeof buffer, value); // shortest round-trip form
return std::string(buffer, result.ptr);
}
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') {
out += '\\';
out += c;
} else if (static_cast<unsigned char>(c) < 0x20) {
char buffer[8];
std::snprintf(buffer, sizeof buffer, "\\u%04x", static_cast<unsigned>(c));
out += buffer;
} else {
out += c;
}
}
return out + "\"";
}
void writeJson(std::ostream& out, const Json& value, const std::string& indent = "") {
const std::string inner = indent + " ";
switch (value.kind) {
case Json::Kind::Null: out << "null"; return;
case Json::Kind::Bool: out << (value.flag ? "true" : "false"); return;
case Json::Kind::Number: out << formatNumber(value.number); return;
case Json::Kind::String: out << quote(value.text); return;
case Json::Kind::Array:
case Json::Kind::Object: {
const bool isObject = value.kind == Json::Kind::Object;
if (value.items.empty()) {
out << (isObject ? "{}" : "[]");
return;
}
out << (isObject ? "{\n" : "[\n");
for (std::size_t i = 0; i < value.items.size(); ++i) {
out << inner;
if (isObject) out << quote(value.keys[i]) << ": ";
writeJson(out, value.items[i], inner);
out << (i + 1 < value.items.size() ? ",\n" : "\n");
}
out << indent << (isObject ? "}" : "]");
}
}
}
Json lesson117() {
const std::vector<std::pair<std::string, double>> weights{{"A", .4}, {"B", .6}};
const std::vector<std::pair<std::string, double>> returns{{"B", .02}, {"A", .01}};
const std::map<std::string, double> byId(returns.begin(), returns.end());
double aligned = 0;
for (const auto& [id, w] : weights) {
const auto it = byId.find(id);
if (it == byId.end()) throw std::runtime_error("Missing asset");
aligned += w * it->second;
}
double positional = 0;
for (std::size_t i = 0; i < weights.size(); ++i) positional += weights[i].second * returns[i].second;
return jobj({{"aligned", jnum(aligned)}, {"positional", jnum(positional)}});
}
int main() {
writeJson(std::cout, lesson117());
std::cout << "\n";
return 0;
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"aligned": 0.016,
"positional": 0.014
}// 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.
//
// Run: rustc -O main.rs && ./main
#![allow(dead_code)]
use std::collections::HashMap;
/// Minimal JSON value; objects keep insertion order.
enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn nums(values: &[f64]) -> Json {
Json::Arr(values.iter().map(|&v| Json::Num(v)).collect())
}
fn optional_nums(values: &[Option<f64>]) -> Json {
Json::Arr(values.iter().map(|v| v.map_or(Json::Null, Json::Num)).collect())
}
fn quote(text: &str) -> String {
let mut out = String::from("\"");
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
// Display for f64 prints the shortest string that round-trips, as JavaScript does.
fn write_json(value: &Json, indent: &str, out: &mut String) {
let inner = format!("{} ", indent);
match value {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) => out.push_str(&format!("{}", n)),
Json::Str(s) => out.push_str("e(s)),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
out.push_str(&inner);
write_json(item, &inner, out);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push(']');
}
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (key, item)) in fields.iter().enumerate() {
out.push_str(&inner);
out.push_str("e(key));
out.push_str(": ");
write_json(item, &inner, out);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push('}');
}
}
}
fn lesson_117() -> Json {
let weights: [(&str, f64); 2] = [("A", 0.4), ("B", 0.6)];
let returns: [(&str, f64); 2] = [("B", 0.02), ("A", 0.01)];
let by_id: HashMap<&str, f64> = returns.iter().cloned().collect();
let aligned = weights.iter().fold(0.0, |s, (id, w)| s + w * by_id.get(id).expect("Missing asset"));
let positional = weights.iter().enumerate().fold(0.0, |s, (i, (_, w))| s + w * returns[i].1);
obj(vec![("aligned", Json::Num(aligned)), ("positional", Json::Num(positional))])
}
fn main() {
let mut out = String::new();
write_json(&lesson_117(), "", &mut out);
println!("{}", out);
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"aligned": 0.016,
"positional": 0.014
}// 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.
//
// Run: dotnet run
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
Console.WriteLine(JsonSerializer.Serialize(Lesson117(), options));
static object Lesson117()
{
var weights = new[] { (id: "A", w: .4), (id: "B", w: .6) };
var returns = new[] { (id: "B", r: .02), (id: "A", r: .01) };
var byId = returns.ToDictionary(x => x.id, x => x.r);
double aligned = weights.Aggregate(0.0, (s, x) =>
byId.TryGetValue(x.id, out double r) ? s + x.w * r : throw new KeyNotFoundException("Missing asset"));
double positional = weights.Select((x, i) => (x, i)).Aggregate(0.0, (s, p) => s + p.x.w * returns[p.i].r);
return new { aligned, positional };
}
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
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