import numpy as np
from scipy import optimize, integrate
from scipy.integrate import solve_ivp

print("问题二：SciPy 科学计算")

# 1. 求非线性方程 x^3 - 2x^2 - 5 = 0 在区间 [2, 4] 内的根
def f(x):
    return x**3 - 2*x**2 - 5

root = optimize.brentq(f, 2, 4)
print("\n1. 非线性方程求根")
print(f"方程 x^3 - 2x^2 - 5 = 0 在 [2, 4] 内的根：x = {root:.6f}")
print(f"验证 f({root:.4f}) = {f(root):.2e}")

# 2. 计算定积分 ∫_0^π sin(x) dx，真实值为 2
result, error = integrate.quad(np.sin, 0, np.pi)
true_value = 2
print("\n2. 定积分计算")
print(f"∫_0^π sin(x) dx 数值结果：{result:.10f}")
print(f"真实值：{true_value}")
print(f"计算误差：{abs(result - true_value):.2e}")

# 3. 求解初值问题：dy/dx = -2y + e^(-x)，y(0) = 1，x ∈ [0, 5]
def ode(x, y):
    return [-2 * y[0] + np.exp(-x)]

x_span = (0, 5)
x_eval = np.linspace(0, 5, 51)
y0 = [1]

sol = solve_ivp(ode, x_span, y0, t_eval=x_eval)

print("\n3. 初值问题数值解（部分输出）")
print(f"{'x':>6}  {'y':>12}")
for i in range(0, len(sol.t), 10):
    print(f"{sol.t[i]:>6.2f}  {sol.y[0][i]:>12.6f}")
