import sympy as sp import math a = int(input("请输入a:")) n0= float(input("请输入n0:")) d = 2 * n0 * a / (1 - a ** 2) p = int(input("请输入p:")) q_sym, nx = sp.symbols('q_sym nx') # 定义符号变量 q1 = a * a * sp.cos(math.radians(p)) * sp.cos(math.radians(p)) * sp.cos(math.radians(q_sym)) ** 2 q2 = (d - a * sp.sin(math.radians(p))) ** 2 q3 = q1 / q2 eq = sp.Eq(q3, 1 - q_sym) # 构造方程 sol = sp.solve(eq, [q_sym, nx]) # 求解 for s in sol: print(sp.N(s)) # 将表达式转换为浮点型以输出结果 上述代码报错TypeError: Cannot convert expression to float,请修改
时间: 2023-11-22 07:51:52 浏览: 80
sympy-docs-pdf-1.7.1.pdf
在代码中,有些表达式是符号表达式,不能直接转换为浮点型。你需要使用 sympy 库提供的 `N()` 方法将符号表达式转换为浮点型。修改代码如下:
```python
import sympy as sp
import math
a = int(input("请输入a:"))
n0 = float(input("请输入n0:"))
d = 2 * n0 * a / (1 - a ** 2)
p = int(input("请输入p:"))
q_sym, nx = sp.symbols('q_sym nx') # 定义符号变量
q1 = a * a * sp.cos(math.radians(p)) * sp.cos(math.radians(p)) * sp.cos(math.radians(q_sym)) ** 2
q2 = (d - a * sp.sin(math.radians(p))) ** 2
q3 = q1 / q2
eq = sp.Eq(q3, 1 - q_sym) # 构造方程
sol = sp.solve(eq, [q_sym, nx]) # 求解
for s in sol:
print(N(s)) # 将表达式转换为浮点型以输出结果
```
阅读全文