Simplest way to solve mathematical equations in Python

后端 未结 15 1604
自闭症患者
自闭症患者 2020-12-13 10:15

I want to solve a set of equations, linear, or sometimes quadratic. I don\'t have a specific problem, but often, I have been in this situation often.

It is simple to

相关标签:
15条回答
  • 2020-12-13 10:36

    Try applying Bisection method in py to find the root given an interval:

    def f(x, rhs): # f(x) = e^x
        return math.e ** x - rhs # e^x = rhs -> e^x - rhs = 0
    
    def solve(rhs, a = 0, b = 100, tol = 1e-3):
        while True:
            c  = (a + b) / 2.0
            if(f(a, rhs) * f(c, rhs) > 0):
                a = c
            else:
                b = c
            if(abs(f(c, rhs)) < tol):
                break
        return c
    
    y = math.e ** 3.75 # x = 3.75
    print(solve(y)) # 3.7499..
    
    0 讨论(0)
  • 2020-12-13 10:39

    You discount the best answer as unacceptable.

    Your question is "I want a free Computer Algebra System that I can use in Python."

    The answer is "SAGE does that."

    Have you looked at maxima/macsyma? SAGE provides bindings for it, and that's one of the more powerful free ones.

    http://maxima.sourceforge.net/

    0 讨论(0)
  • 2020-12-13 10:39

    I'd use Octave for this but I agree, the syntax of Octave isn't what I'd call thrilling (and the docs always confuse me more than they help, too).

    0 讨论(0)
  • 2020-12-13 10:40

    I have just started using GNU Scientific Library, which however is C library. Looks like there are Python bindings too. So, it might be worth looking at.

    0 讨论(0)
  • 2020-12-13 10:42

    Here is how to solve your original question using Python (via Sage). This basically clarifies the remark Paul McMillan makes above.

    sage: a,b,c = var('a,b,c')
    sage: solve([a+b+c==1000, a^2+b^2==c^2], a,b,c)
    [[a == 1000*(r1 + sqrt(r1^2 + 2000*r1 - 1000000))/(r1 + sqrt(r1^2 + 2000*r1 - 1000000) + 1000), b == -1/2*r1 - 1/2*sqrt(r1^2 + 2000*r1 - 1000000) + 500, c == r1], [a == 1000*(r2 - sqrt(r2^2 + 2000*r2 - 1000000))/(r2 - sqrt(r2^2 + 2000*r2 - 1000000) + 1000), b == -1/2*r2 + 1/2*sqrt(r2^2 + 2000*r2 - 1000000) + 500, c == r2]]
    
    0 讨论(0)
  • 2020-12-13 10:43

    Have you looked at SciPy?

    It has an example in the tutorials on solving linear algebra:

    http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html#solving-linear-system

    0 讨论(0)
提交回复
热议问题