"""Inspect secants, centered differences, and stationary points."""
import argparse
from fractions import Fraction as F
import json
import math
import platform
def centered(function, point, step):
if step <= 0:
raise ValueError("step must be positive")
return (function(point+step)-function(point-step))/(2*step)
def main():
options = argparse.ArgumentParser()
options.add_argument("--torch", action="store_true")
args = options.parse_args()
cases = []
versions = {}
def check(name, inputs, operation, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, input=inputs, operation=operation, expected=expected, actual=actual, passed=True))
square = lambda x: x*x
points = list(range(-2,3))
h = F(1,100_000)
slopes = [centered(square,F(x),h) for x in points]
check("quadratic_centered_five_points", [points,str(h)], "use exact centered differences", [-4,-2,0,2,4], [int(x) for x in slopes])
check("tangent_signs", points, "classify five exact slopes", ["fall","fall","flat","rise","rise"],
["fall" if x < 0 else "rise" if x > 0 else "flat" for x in slopes])
check("quadratic_one_sided_secants", [-0.5,-0.1,0.1,0.5], "subtract f(2), divide by signed h",
["7/2","39/10","41/10","9/2"],
[str((square(2+h)-square(2))/h) for h in (F(-1,2),F(-1,10),F(1,10),F(1,2))])
check("centered_can_hide_corner", ["abs",0,"1/100000"], "compare left, right, and centered quotient",
[-1,1,0],[int((abs(-h)-abs(0))/(-h)), int((abs(h)-abs(0))/h), int(centered(abs,F(0),h))])
cubic = lambda x: x*x*x
check("smooth_centered_error_decreases", ["1/2","1/4"], "compute centered differences for x³ at zero",
["1/4","1/16"],[str(centered(cubic,F(0),d)) for d in (F(1,2),F(1,4))])
check("float_steps_can_round_away", [2.0,2**-60], "use binary64 centered difference",
0.0, centered(square,2.0,2**-60))
check("stationary_examples", ["x²","−x²","x³"], "compare values at −1, 0, 1",
[[1,0,1],[-1,0,-1],[-1,0,1]], [[f(x) for x in (-1,0,1)] for f in (square,lambda x:-square(x),cubic)])
distance = lambda t: 30*t*t
check("mean_vs_instantaneous_speed", [0,2], "average distance rate and derivative at the end",
[60,120], [int((distance(2)-distance(0))/2),int(centered(distance,F(2),h))])
check("gradient_update_choices", [-2,2,"eta=1/4"], "update x by subtracting eta times 2x",
[-1,1], [int(x-F(1,4)*2*x) for x in (-2,2)])
if args.torch:
import torch
versions["torch"] = torch.__version__
def gradient(operation, value):
x = torch.tensor(value, dtype=torch.float64, requires_grad=True)
operation(x).backward()
return float(x.grad)
check("relu_autograd_rule", [-1,0,1], "CPU backward pass for ReLU",
[0,0,1], [gradient(torch.relu,x) for x in (-1,0,1)])
sigmoid_at_zero = gradient(torch.sigmoid,0)
check("sigmoid_peak_and_saturation", [-8,0,8], "evaluate CPU backward slopes",
[True,True,True], [gradient(torch.sigmoid,-8)<sigmoid_at_zero,
math.isclose(sigmoid_at_zero,.25,abs_tol=1e-15),
gradient(torch.sigmoid,8)<sigmoid_at_zero])
def repeated_sigmoid(x):
for _ in range(4):
x = torch.sigmoid(x) - .5
return x
check("four_sigmoid_layers_unit_weight", [0,4], "differentiate four centered sigmoid layers",
.25**4, gradient(repeated_sigmoid,0))
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=cases)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。
入口文件:projects/ai-math-derivative-intro-lab/derivative-observations.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
derivative-observations.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a48.zip