我正在尝试为 b 求解具有多个变量的方程式

I am trying to solve an equation with multiple variables for b

我正在尝试求解一个简单的方程式,但输出结果如下:

等式是y = m*x + b,

ymb 已定义

我要打印 b

import sympy
while True:
    x1 = int(input('x1: '))
    y1 = int(input('y1: '))

    x2 = int(input('x1: '))
    y2 = int(input('y1: '))

    m = (y1-y2) / (x1-x2)
    print(m)
    
    m = sympy.symbols('m')
    x = sympy.symbols('x')
    y = sympy.symbols('y')
    b = sympy.symbols('b')
    
    a = y, x*m + b
    
    print(sympy.solve(a, b))

你可以试试:

import sympy
# while True:
x1 = int(input('x1: '))
y1 = int(input('y1: '))

x2 = int(input('x1: '))
y2 = int(input('y1: '))

m = (y1-y2) / (x1-x2)
print(f"m: {m}")

b = sympy.symbols('b')

a = y, x*m + b

print(sympy.solve(y1 -x1*m - b, b))

测试:

x1: 1
y1: 7
x1: 2
y1: 12
m: 5.0
# out: [2.00000000000000]

我们需要给 sympy 两个等式,每个等式一个 x,y 组合。首先,创建一般直线方程 a = Eq(y, x*m + b)。然后将 xy 的各个值替换为两个方程式。

import sympy

x1, y1 = 1, 4
x2, y2 = 5, 8

x, y, m, b = sympy.symbols('x y m b')

a = sympy.Eq(y, x * m + b)
eq1 = a.subs({x: x1, y: y1})  # Eq(4, b + m)
eq2 = a.subs({x: x2, y: y2})  # Eq(8, b + 5*m)
print(sympy.solve([eq1, eq2], (m, b)))  # {m: 1, b: 3}