"""Chapter 2: data and answers for the examples and exercises (constructed data). Section 2.2: a record of 100 judgments (1 = correct, 0 = wrong) with 71 correct, built with a fixed seed; the first 40 questions are math, the remaining 60 reading. Exercise 2.1: a 20-row CSV of model answers and correct answers. Section 2.3 and exercise 2.2: values of y = (x - 3)^2, numerical slopes, and descent steps. Standard library only (the book's own programs use NumPy; this script checks their numbers). """ import random print("--- section 2.2: 100 judgments ---") rng = random.Random(7) wrong = set(rng.sample(range(100), 29)) record = "".join("0" if i in wrong else "1" for i in range(100)) for i in range(0, 100, 50): print(f' "{record[i:i + 50]}"') print(f"correct {record.count('1')}/100 = {record.count('1') / 100}") math_part, read_part = record[:40], record[40:] print(f"math (first 40): {math_part.count('1')}/40 = {math_part.count('1') / 40}") print(f"reading (last 60): {read_part.count('1')}/60 = {read_part.count('1') / 60:.4f}") print("\n--- exercise 2.1: answers.csv ---") truth = "ACBDABCDDACBADBCABDC" model = "ACBDCBCDAACBBDBCADDA" print("model_answer,correct_answer") for m, t in zip(model, truth): print(f"{m},{t}") same = sum(m == t for m, t in zip(model, truth)) print(f"correct {same}/{len(truth)} = {same / len(truth)}; wrong rows (1-based):", [i + 1 for i, (m, t) in enumerate(zip(model, truth)) if m != t]) print("\n--- section 2.3 / exercise 2.2: y = (x - 3)^2 ---") def f(x): return (x - 3) ** 2 def slope(x, h=0.001): return (f(x + h) - f(x)) / h for k in range(0, 13): x = k / 2 print(f"x = {x:3.1f} y = {f(x):5.2f}") for x in (1, 2, 4, 5): print(f"slope at {x}: {slope(x):.3f}") for x in (1, 5): print(f"secant from {x} to {x + 1}: {f(x + 1) - f(x)}") print("\n--- descent from x = 0, step 0.1 (numerical slope) ---") x = 0.0 for i in range(1, 31): x = x - 0.1 * slope(x) if i in (1, 2, 3, 10, 20, 30): print(f"step {i:2d}: x = {x:.3f}, f(x) = {f(x):.4f}") print("\n--- exercise 2.2: descent from x = 5, step 0.1 ---") x = 5.0 for i in range(1, 4): s = slope(x) x = x - 0.1 * s print(f"step {i}: slope {s:.4f}, new x = {x:.4f}, f(x) = {f(x):.4f}") print("\n--- section 2.4: exact derivative 2(x - 3), several step sizes ---") for step in (0.1, 0.5, 1.0, 1.1): x = 0.0 path = [] for _ in range(6): x = x - step * 2 * (x - 3) path.append(round(x, 2)) print(step, path)