如何在Python中没有任何模块的情况下求解方程式?

时间:2018-08-22 10:11:41

标签: python-3.x

我想在没有任何模块(NumPy,Sympy等)的情况下求解此方程

Px + Qy = W

(例如5x + 6y = 55)

谢谢。

2 个答案:

答案 0 :(得分:1)

使用python解决方程式的方法有数千种。

其中之一是:

def myfunc (x=None, y=None):
    return ((55-6*y)/5.0) if y else ((55-5*x)/6.0)


print(myfunc(x=10)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42)) # OUTPUT: -39.4, x value for y == 42

您只需在函数内定义求解方程式所需的步骤。
在我们的示例中,如果我们有y的值,则将6*y减去55,然后除以5.0(我们将.0加为浮点数),否则(意味着我们有x)我们从5*x中减去55,然后除以6.0

使用相同的原理,可以概括一下:

def myfunc (x=None, y=None, P=None, Q=None, W=None):
    if not W:
        return P*x + Q*y
    elif not x:
        return (W-Q*y)/float(P)
    elif not y:
        return (W-P*x)/float(Q)
    elif not P:
        return (W-Q*y)/float(x)
    elif not Q:
        return (W-P*x)/float(y)


print(myfunc(x=10, P=5, Q=6, W=55)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42, P=5, Q=6, W=55)) # OUTPUT: -39.4, x value for y == 42

检查this QA中是否有其他有趣的方法来解决此问题

答案 1 :(得分:0)

这是一种非常粗糙的方法,但是您可以使用蛮力技术,正如我在问题下方的评论中所说。可能可以对其进行很多优化,仅提供int个输出,但总体显示了该方法:

import numpy as np

# Provide the equation:
print("Provide a, b and c to evaluate in equation of form {ax + by - c = 0}")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

x_range = int(input("x-searching range (-a, a): "))
y_range = int(input("y-searching range (-b, b): "))
error = float(input("maximum accepted error from the exact solution: "))

x_range = np.arange(-x_range, x_range, 1)
y_range = np.arange(-y_range, y_range, 1)

for x in x_range:
    for y in y_range:
        if -error <= a * x + b * y - c <= error:
            print("Got an absolute error of {} or less with numbers x = {} and y = {}.".format(error, x, y))

a = 1b = 2c = 3x_range = 10y_range = 10error = 0.001的示例输出:

Got an error of 0.001 or less with numbers x = -9 and y = 6.
Got an error of 0.001 or less with numbers x = -7 and y = 5.
Got an error of 0.001 or less with numbers x = -5 and y = 4.
Got an error of 0.001 or less with numbers x = -3 and y = 3.
Got an error of 0.001 or less with numbers x = -1 and y = 2.
Got an error of 0.001 or less with numbers x = 1 and y = 1.
Got an error of 0.001 or less with numbers x = 3 and y = 0.
Got an error of 0.001 or less with numbers x = 5 and y = -1.
Got an error of 0.001 or less with numbers x = 7 and y = -2.
Got an error of 0.001 or less with numbers x = 9 and y = -3.

我正在使用numpy,但不是使用内置函数来求解方程本身,而只是创建一个数组。当然,没有它也可以做到。