"""Compute the chapter's algebra examples with fixed inputs and independent checks."""
from fractions import Fraction as F
from json import dumps
from math import exp, isclose, log, log2, sqrt
from platform import python_version
def real_roots(a, b, c):
if a == 0:
if b != 0:
return [-c / b]
return "all real numbers" if c == 0 else []
discriminant = b*b - 4*a*c
if discriminant < 0:
return []
if discriminant == 0:
return [-b/(2*a)]
distance = sqrt(discriminant)
return sorted([(-b-distance)/(2*a), (-b+distance)/(2*a)])
def partial_sum(first, ratio, count):
return sum((first * ratio**k for k in range(count)), F(0))
def run():
cases = []
def check(name, inputs, expected, actual):
if expected != actual:
raise AssertionError(f"{name}: expected {expected!r}, got {actual!r}")
cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))
slope, offset, rhs = 4, -7, 21
answer = F(rhs-offset, slope)
check("linear_equation_reversible_steps", [4, -7, 21], ["7", True],
[str(answer), slope*answer + offset == rhs])
root_inputs = [(1, -1, -6), (1, 6, 9), (1, 1, 2), (-1, 1, 6)]
check("quadratic_sign_cases_and_negative_opening", root_inputs, [[-2,3],[-3],[],[-2,3]],
[real_roots(*args) for args in root_inputs])
values = real_roots(1, -7, 12)
check("factoring_produces_all_roots", "x² − 7x + 12", [[3,4],[0,0]],
[values, [(x-3)*(x-4) for x in values]])
check("zero_leading_coefficient_has_separate_cases", [(0,4,-8), (0,0,0), (0,0,1)],
[[2],"all real numbers",[]], [real_roots(*args) for args in ((0,4,-8),(0,0,0),(0,0,1))])
candidates = (2, 3)
valid = [x for x in candidates if x != 2 and F((x-2)*(x-3),x-2)==0]
check("clearing_denominator_requires_original_domain", "(x−2)(x−3)/(x−2)=0",
[[2,3],[3]], [list(candidates),valid])
samples = (1,2,3)
check("negative_divisor_flips_strictness_and_direction", "−4x+8≤0 and −2x+4>0",
[[False,True,True],[False,True,True],[True,False,False],[True,False,False]],
[[f(x) for x in samples] for f in (lambda x: -4*x+8 <= 0, lambda x: x >= 2,
lambda x: -2*x+4 > 0, lambda x: x < 2)])
check("inequality_intersection", "−1<x<3", [0,1,2],
[x for x in range(-3,5) if x > -1 and x < 3])
x = 4
check("complete_square_and_substitution", dict(x=x, example="x²−6x"),
[x*x-6*x, 0, 16], [(x-3)**2-9, (x-3)**2-1, (x*x-12)**2])
errors = []
for evaluate in (lambda: 1/0, lambda: sqrt(-1), lambda: log(0)):
try:
evaluate()
except (ZeroDivisionError, ValueError) as problem:
errors.append(type(problem).__name__)
check("denominator_square_root_and_log_domains", "denominator zero, sqrt negative, log zero",
["ZeroDivisionError", "ValueError", "ValueError"], errors)
f = lambda t: 3*t
g = lambda t: t*t-2
check("composition_order_native_exercise", [2, "f(t)=3t; g(t)=t²−2"], [6,34], [f(g(2)),g(f(2))])
check("quadratic_and_sigmoid_ranges", [-3,0,3], [[9,0,9],[True,0.5,True]],
[[i*i for i in (-3,0,3)], [0<1/(1+exp(3)), 1/(1+exp(0)), 1/(1+exp(-3)) < 1]])
a,m,n = 2,3,4
check("five_exponent_rules", [a,m,n], [True]*5,
[a**m*a**n==a**(m+n), F(a**m,a**n)==F(1,a), (a**m)**n==a**(m*n), F(a)**-n==F(1,a**n),a**0==1])
check("log_rules_and_exercise", [16,2], [5,True,True,True,1,0],
[log2(16*2),log2(16*2)==log2(16)+log2(2),log2(16/2)==log2(16)-log2(2),
log2(16**2)==2*log2(16), log2(2),log2(1)])
check("valid_bases_are_reflections", [0.5,2,3], [True]*3,
[isclose(log(base**2)/log(base),2) for base in (0.5,2,3)])
probs = [0.7,0.3]
check("loss_penalty_and_entropy_distinct", [0.5,0.1,probs], [True,True,True],
[-log(0.1)>-log(0.5),-log(1)==0, -sum(p*log2(p) for p in probs)>0])
arithmetic = [3+4*k for k in range(4)]
geometric = [3*2**k for k in range(4)]
check("sequence_terms_and_finite_sums", [3,4,2], [[3,7,11,15],36,[3,6,12,24],45,"12"],
[arithmetic,sum(arithmetic),geometric,sum(geometric),str(partial_sum(F(3),F(1),4))])
sums = [partial_sum(F(1),F(1,2),count) for count in (2,4,6)]
check("geometric_convergence_and_divergent_boundaries", ["r=1/2","r=−1","r>1"],
[["3/2","15/8","63/32"],["1","0","1","0"],True],
[[str(number) for number in sums], [str(partial_sum(F(1),F(-1),count)) for count in range(1,5)],
partial_sum(F(1), F(5,4),12)>partial_sum(F(1), F(5,4),10)])
check("geometric_series_exercise_and_gradient_products", [F(1,4),0.5,2], ["4/3",0.00390625,256],
[str(1/(1-F(1,4))),0.5**8,2**8])
return dict(version=python_version(), cases=cases)
if __name__ == "__main__":
print(dumps(run(), default=str))
本例需在 Windows、Python 3.12.14、Chromium、标准浏览器 API。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、Chromium、标准浏览器 API。
入口文件:projects/ai-math-algebra-lab/algebra-numerics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
algebra-numerics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、Chromium、标准浏览器 API。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a32.zip