关于一元多次方程
2026-03-07 13:32:41
发布于:浙江
在这个AI盛行的年代,只有少量帖子还是作者一字一句认真写的!
能不能给我点一个不要钱的赞吗??
一元一次方程这个东东你们都在七年级学过了,我就不多说了
一元二次方程可以用下面的方法解:
1.
2.
3.
这是我在一个视频上看到的:
接下来是三次方程:
四次方程我还不太会,你的点赞是我最大的动力!
接下来:
请问我给你一个方程,你如何解出根来?
别急,万一是5次方程你就不能用系数了!
那怎么办呢?
请看:
如果想要一个完整的代码,我这里有:
from math import *
# --- 构建全局安全字典 ---
SAFE_DICT = {'x': 0}
for name, obj in list(globals().items()):
if not name.startswith('_'):
if callable(obj):
SAFE_DICT[name] = obj
elif isinstance(obj, (float, int)) and name in ['pi', 'e']:
SAFE_DICT[name] = obj
SAFE_DICT['inf'] = float('inf')
SAFE_DICT['-inf'] = float('-inf')
def solve(f, x0=0.5, max_iter=2000, init_step=0.1):
"""
寻找函数 f 的根所在的区间 [a, b]
"""
f0 = f(x0)
# 检查起点本身是否已经是解 (且不是因为下溢变成的0)
if abs(f0) < 1e-10 and isfinite(f0):
# 额外检查:如果 x0 是一个很大的负数,且函数是 exp,我们怀疑是下溢
if abs(x0) > 100 and f0 == 0.0:
pass # 把它当作非解处理
else:
print(f"探测: 起点即为精确解 x = {x0}")
return (x0, x0)
step = init_step
# --- 智能方向判定 ---
try:
f_positive = f(x0 + init_step)
if not isfinite(f_positive) or (abs(x0 + init_step) > 100 and f_positive == 0.0):
f_positive = 1e10
except:
f_positive = 1e10
try:
f_negative = f(x0 - init_step)
if not isfinite(f_negative) or (abs(x0 - init_step) > 100 and f_negative == 0.0):
f_negative = 1e10
except:
f_negative = 1e10
if f_positive < f_negative:
direction = 1
print(f"智能判定: 优先正向探索")
else:
direction = -1
print(f"智能判定: 优先负向探索")
tried_reverse = False
best_x, best_f = x0, f0
MIN_STEP = 1e-9
for i in range(max_iter):
x1 = x0 + step * direction
# --- 防止 x1 过于接近 0 ---
MIN_X = 1e-8
if abs(x1) < MIN_X:
x1 = MIN_X if x1 >= 0 else -MIN_X
try:
f1 = f(x1)
# --- 关键修复: 检查是否因为下溢导致的 0 ---
# 如果 x 是很大的负数,且 f(x) 是 0,我们认为这是下溢,不是根
if abs(x1) > 100 and f1 == 0.0:
raise OverflowError("Underflow (f(x) is too small)")
if not isfinite(f1):
raise ValueError("Function value is infinite or NaN")
except:
step = abs(step) * 0.5
if abs(step) < MIN_STEP:
direction *= -1
step = init_step
continue
# --- 修复: 只有当 f1 有效时才判断 ---
# 1. 核心判断:变号
if f0 * f1 < 0:
a, b = min(x0, x1), max(x0, x1)
if abs(a - b) < 1e-10:
mid = (a + b) / 2
print(f"捷径: 区间极度收缩,直接返回中点 x = {mid}")
return (mid, mid)
print(f"找到区间: ({a}, {b})")
return (a, b)
# 2. 更新历史最佳点 (修复: 排除下溢点)
current_f_abs = abs(f1)
best_f_abs = abs(best_f)
# 如果 f1 是 0 但其实是下溢,给它一个很大的值
if abs(x1) > 100 and f1 == 0.0:
current_f_abs = 1e10
if current_f_abs < best_f_abs:
best_x, best_f = x1, f1
# 3. 趋势正确,加速
if abs(f1) < abs(f0):
x0, f0 = x1, f1
if abs(step) < 1e6:
step = abs(step) * 1.5
continue
# 4. 趋势错误,缩步
if abs(step) > MIN_STEP:
step = abs(step) * 0.5
else:
if not tried_reverse:
print("探测: 步长过小,尝试反向")
direction *= -1
step = init_step
x0, f0 = best_x, best_f
tried_reverse = True
else:
if init_step > 1e5:
print("探测: 搜索范围已达上限。")
# --- 关键修复: 判断是否有实数根 ---
try:
f_best = f(best_x)
# 如果是因为下溢变成0,也判定为无根
if (abs(best_x) > 100 and f_best == 0.0) or abs(f_best) > 1e-3:
print(f"探测: 在最佳点 x={best_x} 处的函数值为 {f_best}")
print("结论: 函数值远离 0 或因下溢显示为0,判定为无实数根。")
return None
else:
print(f"探测: 使用历史最佳近似解 x={best_x}")
return (best_x, best_x)
except:
print("结论: 无法计算函数值,判定为无实数根。")
return None
print("探测: 双向探索失败,扩大搜索范围")
init_step *= 10
step = init_step
direction = 1 if direction == -1 else -1
tried_reverse = False
print("达到最大迭代次数")
return None
def diff(f, x):
h = 1e-8
try:
return (f(x+h) - f(x)) / h
except:
return 1e-8
def nd(f, t, max_iter=100, tol=1e-12):
# --- 1. 特殊处理 ---
if t[0] == t[1]:
x = t[0]
if abs(x) < 1e-8:
try:
f0 = f(0)
if abs(f0) < 1e-10:
print("捷径: 检测到边界根 x = 0")
return 0
except:
pass
x0 = x
else:
x0 = (t[0] + t[1]) / 2
x = x0
# --- 2. 线性捷径 ---
try:
x1 = x0
x2 = x0 + 1e-3
f1 = f(x1)
f2 = f(x2)
a = (f2 - f1) / (x2 - x1)
if abs(a) > 1e-15:
root = x1 - f1 / a
if abs(f(root)) < tol * 100:
return root
except:
pass
# --- 3. 标准牛顿法迭代 ---
for i in range(max_iter):
try:
if not isfinite(x):
break
fx = f(x)
dfx = diff(f, x)
if not isfinite(dfx) or abs(dfx) < 1e-15:
break
x_new = x - fx / dfx
if not isfinite(x_new):
for shrink in [2, 4, 8, 16]:
x_temp = x - (fx / dfx) / shrink
if isfinite(x_temp):
x_new = x_temp
break
if not isfinite(x_new):
break
# --- 移除对负数的强制修正 ---
# 让牛顿法自己跑,如果跑偏了就结束
if abs(x_new - x) < tol:
return x_new
x = x_new
except Exception as e:
break
# --- 移除了强制返回0的逻辑 ---
# 如果x是负数,说明没找到好解,直接返回x
return x
# --- 主程序 ---
if __name__ == "__main__":
user_input = input("请输入函数(例如 x**3 - 2*x - 5): ").strip()
# 重新编译用户输入的表达式
try:
code = compile(user_input, '<string>', 'eval')
except Exception as e:
print(f"输入的函数语法错误: {e}")
exit()
def equation(x):
SAFE_DICT['x'] = x
try:
result = float(eval(code, {"__builtins__": {}}, SAFE_DICT))
if isfinite(result):
return result
else:
return float('inf')
except (ValueError, OverflowError):
return float('inf')
# --- 智能初始值 ---
x0_start = 0.5
if 'sqrt' in user_input or 'log' in user_input:
x0_start = 0.1
result = solve(equation, x0=x0_start)
if result is None:
print("系统判定: 该函数在实数域内无解。")
elif result:
print(f"根位于区间: {result}")
root = nd(equation, result)
if root is not None:
try:
val = equation(root)
residual = abs(val)
print(f"求得根: {root}")
print("验证 f(%.20f) = %.20f" % (root, val))
if residual > 1e-3:
print("警告: 残差较大,此为近似解或函数无实数根。")
except:
print(f"求得根: {root}")
print("验证 f(%.20f) = 无效值 (可能超出定义域)" % root)
print("警告: 函数在该点无定义。")
else:
print("未能通过牛顿法找到根。")
else:
print("未能找到包含根的区间。")
print("提示: 函数可能没有实数根(例如 exp(x) 恒大于 0)。")
这里空空如也



















有帮助,赞一个