在 Python 中求解数学方程的最简单方法

发布于 2024-08-09 02:37:59 字数 378 浏览 4 评论 0原文

我想求解一组方程,线性方程,有时是二次方程。我没有什么具体的问题,但我经常遇到这种情况。

使用 wolframalpha.com(Mathematica 的网络版)来解决这些问题很简单。但这并不能提供 iPython shell 的舒适性和便利性。

是否有一个简单的库可以在 python shell 中处理线性和二次方程?

就我个人而言,我发现使用Casio 991 MS科学计算器非常方便。我知道如何设置变量、解方程以及做很多事情。我想要这样一个工具,最好可以在 ipython shell 中使用。我很惊讶没有找到任何东西。我对圣人印象不够深刻;也许我错过了一些东西。

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 use wolframalpha.com, the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenience of an iPython shell.

Is there a simple library to work on linear and quadratic equations from a python shell?

Personally, I find it extremely convenient to use the Casio 991 MS scientific calculator. I know how to set variables, solve equations, and do a lot. I want such a tool preferably usable from within an ipython shell. I am surprised not to have found any. I'm not impressed enough by sage; perhaps I am missing something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

还给你自由 2024-08-16 02:37:59

sympy 正是您正在寻找的。

sympy is exactly what you're looking for.

乞讨 2024-08-16 02:37:59

您认为最佳答案不可接受。

你的问题是“我想要一个可以在 Python 中使用的免费计算机代数系统。”

答案是“SAGE 就是这么做的”。

你看过 maxima/macsyma 吗? SAGE 为其提供了绑定,这是更强大的免费绑定之一。

http://maxima.sourceforge.net/

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/

避讳 2024-08-16 02:37:59

以下是如何使用 Python(通过 Sage)解决您原来的问题。这基本上澄清了保罗·麦克米兰的上述言论。

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]]

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]]
小姐丶请自重 2024-08-16 02:37:59

对于不精确的解决方案,请阅读线性规划顺序二次优化,然后搜索为您执行此类优化的 Python 库。

如果方程需要整数解,您应该搜索 Python 的丢番图方程求解器。

请注意,对欧拉项目使用简单的求解器没有抓住要点。有趣且有教育意义的部分是学习如何使用原始方法自己解决它!

For inexact solutions, read up on linear programming and sequential quadratic optimization, then search for Python libraries that performs such optimizations for you.

If the equations require integer solutions, you should search for Diophantine equation solvers for Python.

Just note that using a simple solver for Project Euler is missing the point. The fun, and educational part, is learning how to solve it yourself using primitive methods!

暮年慕年 2024-08-16 02:37:59

APMonitor.com 是一个用于求解大规模非线性方程组(超过 100 万个)的免费网络服务。有一个浏览器界面和一个 Python / MATLAB API。 Python 的 API 是单个脚本 (apm.py),可以从 apmonitor.com 主页下载。将脚本加载到 Python 代码中后,它就能够解决以下问题:

  • 非线性方程
  • 微分方程和代数方程
  • 最小二乘模型拟合
  • 移动水平估计
  • 非线性模型预测控制
  • 等。

对于新用户,APM Python 软件有一个 Google用户可以在其中发布问题的群组论坛。每两周举办一次网络研讨会,展示运筹学和工程中的优化问题。

以下是优化问题的示例 (hs71.apm)。

Model

  Variables

    x[1] = 1, >=1, <=5

    x[2] = 5, >=1, <=5

    x[3] = 5, >=1, <=5

    x[4] = 1, >=1, <=5

  End Variables



  Equations

    x[1] * x[2] * x[3] * x[4] > 25

    x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2 = 40



    minimize  x[1] * x[4] * (x[1]+x[2]+x[3]) + x[3]

  End Equations

End Model

优化问题通过以下Python脚本解决:

# Import

from apm import *

# Select server

server = 'http://xps.apmonitor.com'

# Application name

app = 'eqn'

# Clear previous application

apm(server,app,'clear all')

# Load model file

apm_load(server,app,'hs71.apm')

# Option to select solver (1=APOPT, 2=BPOPT, 3=IPOPT)

apm_option(server,app,'nlc.solver',3)

# Solve on APM server

solver_output = apm(server,app,'solve')


# Display solver output

print solver_output


# Retrieve results

results = apm_sol(server,app)

# Display results

print '--- Results of the Optimization Problem ---'

print results

# Display Results in Web Viewer 

url = apm_var(server,app)

print "Opened Web Viewer: " + url

A free web-service for solving large-scale systems of nonlinear equations (1 million+) is APMonitor.com. There is a browser interface and an API to Python / MATLAB. The API to Python is a single script (apm.py) that is available for download from the apmonitor.com homepage. Once the script is loaded into a Python code, it gives the ability to solve problems of:

  • Nonlinear equations
  • Differential and algebraic equations
  • Least squares model fitting
  • Moving horizon estimation
  • Nonlinear model predictive control
  • etc.

For the new user, the APM Python software has a Google Groups forum where a user can post questions. There are bi-weekly webinars that showcase optimization problems in operations research and engineering.

Below is an example of an optimization problem (hs71.apm).

Model

  Variables

    x[1] = 1, >=1, <=5

    x[2] = 5, >=1, <=5

    x[3] = 5, >=1, <=5

    x[4] = 1, >=1, <=5

  End Variables



  Equations

    x[1] * x[2] * x[3] * x[4] > 25

    x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2 = 40



    minimize  x[1] * x[4] * (x[1]+x[2]+x[3]) + x[3]

  End Equations

End Model

The optimization problem is solved with the following Python script:

# Import

from apm import *

# Select server

server = 'http://xps.apmonitor.com'

# Application name

app = 'eqn'

# Clear previous application

apm(server,app,'clear all')

# Load model file

apm_load(server,app,'hs71.apm')

# Option to select solver (1=APOPT, 2=BPOPT, 3=IPOPT)

apm_option(server,app,'nlc.solver',3)

# Solve on APM server

solver_output = apm(server,app,'solve')


# Display solver output

print solver_output


# Retrieve results

results = apm_sol(server,app)

# Display results

print '--- Results of the Optimization Problem ---'

print results

# Display Results in Web Viewer 

url = apm_var(server,app)

print "Opened Web Viewer: " + url
彩虹直至黑白 2024-08-16 02:37:59

您看过 SciPy 吗?

它在解决线性代数的教程中有一个示例:

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

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

2024-08-16 02:37:59

供参考:Wolfram Alpha 的解决方案

a-1000!=0,   b = (1000 (a-500))/(a-1000),   c = (-a^2+1000 a-500000)/(a-1000)

在 python 中,使用 sympy 的求解器module(请注意,它假设所有方程都设置为零):

>>> import sympy
>>> a, b, c = sympy.symbols('a, b, c')
>>> sympy.solve([a + b + c - 1000, a**2 + b**2 - c**2], b, c)
[(1000*(a - 500)/(a - 1000), (-a**2 + 1000*a - 500000)/(a - 1000))]

当然,a != 1000,因为 a-1000 是两个方程的分母。

For reference: Wolfram Alpha's solution:

a-1000!=0,   b = (1000 (a-500))/(a-1000),   c = (-a^2+1000 a-500000)/(a-1000)

In python, using sympy's solver module (note that it assumes all equations are set equal to zero):

>>> import sympy
>>> a, b, c = sympy.symbols('a, b, c')
>>> sympy.solve([a + b + c - 1000, a**2 + b**2 - c**2], b, c)
[(1000*(a - 500)/(a - 1000), (-a**2 + 1000*a - 500000)/(a - 1000))]

And of course, a != 1000, as a-1000 is the denominator of the two equations.

拥有 2024-08-16 02:37:59

我刚刚开始使用 GNU Scientific Library,但它是 C 库。看起来也有 Python 绑定 。所以,这可能值得一看。

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.

你与昨日 2024-08-16 02:37:59

我会使用 Octave 来实现此目的,但我同意,Octave 的语法不是这样的我觉得令人兴奋(而且文档总是让我困惑而不是提供帮助)。

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).

稚然 2024-08-16 02:37:59

SymPy 符号 Python 库演示:以符号方式求解数学和积分漂亮地打印输出

来自@Autoplectic:

sympy 正是您正在寻找的。

虽然我倾向于在 Stack Overflow 上写一些最长的答案,但这是我在 Stack Overflow 上看到的最短的答案。

让我们添加一个基本的演示。

您需要的参考资料和教程:

  1. https://www.sympy.org/en/index. html -->点击“开始使用教程”
    1. 教程索引:https://docs.sympy.org/latest/tutorial/ index.html 示例页面:
      1. 基本操作
      2. 打印
      3. 简化
      4. 微积分

我想出的微积分演示(请参阅< a href="https://docs.sympy.org/latest/tutorial/calculus.html" rel="nofollow noreferrer">此处查看我开始使用的主要教程):

简短版本:

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
print(pretty(integral))
result = integral.doit() # "do it": evaluate the integral
print(pretty(result))

较长版本:

eRCaGuy_hello_world/math/sympy_integral_and_printing.py

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

# Store an integral
integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
# print it in various ways
print("ORIGINAL INTEGRAL:")
print(pretty(integral))
pprint(integral)        # "pretty print": same as above
print(pretty(integral, use_unicode=False))  # pretty print with ASCII instead 
                                            # of unicode
print(integral)         # plain text
print(latex(integral))  # in LaTeX format

# Now solve the integral and output the result by telling it to
# "do it".
result = integral.doit()
# print it in various ways
print("\nRESULT:")
print(pretty(result))
pprint(result)
print(pretty(result, use_unicode=False))
print(result)
print(latex(result))

请注意,使用 pprint(integral)print(pretty(integral)) 相同。

运行上述命令的输出:

ORIGINAL INTEGRAL:
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
 oo  oo                 
  /   /                 
 |   |                  
 |   |      2    2      
 |   |   - x  - y       
 |   |  e          dx dy
 |   |                  
/   /                   
-oo -oo                 
Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty} e^{- x^{2} - y^{2}}\, dx\, dy

RESULT:
π
π
pi
pi
\pi

Python 中的 SymPy 符号数学库几乎可以执行任何类型的数学运算,求解方程、简化、因式分解、用变量替换值、漂亮的打印、转换为 LaTeX 格式等。到目前为止,在我非常有限的使用中,它是一个非常强大的求解器。我建议尝试一下。

对我来说,安装它(在 Linux Ubuntu 上测试)非常简单:

pip3 install sympy

SymPy symbolic Python library demo: symbolically solving math and integrals & pretty-printing the output

From @Autoplectic:

sympy is exactly what you're looking for.

While I have a tendency to write some of the longest answers on Stack Overflow, that is the shortest answer I've seen on Stack Overflow.

Let's add a basic demo.

References and tutorials you'll need:

  1. https://www.sympy.org/en/index.html --> click "Get started with the tutorial"
    1. Tutorial index: https://docs.sympy.org/latest/tutorial/index.html Example pages:
      1. Basic Operations
      2. Printing
      3. Simplification
      4. Calculus

Calculus demo I came up with (see here for the main tutorial I looked at to get started):

Short version:

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
print(pretty(integral))
result = integral.doit() # "do it": evaluate the integral
print(pretty(result))

Longer version:

eRCaGuy_hello_world/math/sympy_integral_and_printing.py:

#!/usr/bin/env python3

from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

# Store an integral
integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
# print it in various ways
print("ORIGINAL INTEGRAL:")
print(pretty(integral))
pprint(integral)        # "pretty print": same as above
print(pretty(integral, use_unicode=False))  # pretty print with ASCII instead 
                                            # of unicode
print(integral)         # plain text
print(latex(integral))  # in LaTeX format

# Now solve the integral and output the result by telling it to
# "do it".
result = integral.doit()
# print it in various ways
print("\nRESULT:")
print(pretty(result))
pprint(result)
print(pretty(result, use_unicode=False))
print(result)
print(latex(result))

Note that using pprint(integral) is the same as print(pretty(integral)).

Output of running the above commands:

ORIGINAL INTEGRAL:
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
∞  ∞                  
⌠  ⌠                  
⎮  ⎮      2    2      
⎮  ⎮   - x  - y       
⎮  ⎮  ℯ          dx dy
⌡  ⌡                  
-∞ -∞                 
 oo  oo                 
  /   /                 
 |   |                  
 |   |      2    2      
 |   |   - x  - y       
 |   |  e          dx dy
 |   |                  
/   /                   
-oo -oo                 
Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty} e^{- x^{2} - y^{2}}\, dx\, dy

RESULT:
π
π
pi
pi
\pi

The SymPy symbolic math library in Python can do pretty much any kind of math, solving equations, simplifying, factoring, substituting values for variables, pretty printing, converting to LaTeX format, etc. etc. It seems to be a pretty robust solver in my very limited use so far. I recommend trying it out.

Installing it, for me (tested on Linux Ubuntu), was as simple as:

pip3 install sympy
梦毁影碎の 2024-08-16 02:37:59

我认为没有一种统一的方法可以同时处理线性和二次(或通常非线性)方程。对于线性系统,Python 绑定了线性代数和矩阵包。非线性问题往往根据具体情况来解决。

I don't think there is a unified way of dealing with both linear and quadratic (or generally nonlinear) equations simultaneously. With linear systems, python has bindings to linear algebra and matrix packages. Nonlinear problems tend to be solved on a case by case basis.

墨离汐 2024-08-16 02:37:59

这取决于您的需求:

如果您想要交互式图形界面,那么 sage 可能是最好的解决方案。

如果您想避免使用图形界面,但仍然想做计算机代数,那么 sympy 或 maxima 可能可以满足您的需求。 (sympy看起来很有前途,但要取代mathematica还有很长的路要走)。

如果您并不真正需要符号代数,但需要一种使用矩阵进行编程、求解微分方程和最小化函数的方法,那么 scipy 或 Octave 是很好的起点。

It depends on your needs:

If you want an interactive graphical interface, then sage is probably the best solution.

If you want to avoid using a graphical interface, but you still want to do computer algebra, then sympy or maxima may cover your needs. (sympy looks very promising, but it still have a long way to go before they can replace mathematica).

If you don't really need symbolic algrebra, but you need a way to program with matrices, solve differential equations, and minimize functions, then scipy or octave are excelent starting points.

尝蛊 2024-08-16 02:37:59

看看这个:

http://openopt.org/FuncDesignerDoc#Solving_systems_of_nonlinear_equations

它非常容易使用并且相当强大

Take a look at this:

http://openopt.org/FuncDesignerDoc#Solving_systems_of_nonlinear_equations

It is extremely easy to use and quite powerful

呆头 2024-08-16 02:37:59

好吧,我只是偶然用谷歌搜索到这个页面。我看到很多关于这个和那个软件工具的建议,但是有任何工具实际上提供了答案吗?实际答案是:

[a,b,c] = [200,375,425]

我是怎么得到这个的?通过用 Maxima 编程语言编写一个快速程序,通过“强力”搜索找到它。看我对千里马语言的熟悉程度,只花了10分钟左右。程序运行了几秒钟。这是程序:

euler_solve():= block

[a, b, A, B, end:1000],

for a thru end do
    (
    for b thru end do
        (
        c: 1000 -a -b,
        if c < 0 then
            b:end
        else if a^2 + b^2 = c^2 then
            (
            A:a,
            B:b,
            a:end,
            b:end
            )
        )
    ),
return( [A,B,c])
);

您可以将上面的代码剪切并粘贴到wxMaxima用户界面中,我在Ubuntu而不是MS Windows下运行该界面。然后你只需输入函数名称:euler_solve(),按回车键,等待几秒钟,就会弹出答案。这种特殊类型的问题非常简单,您可以使用任何通用编程语言来进行搜索。

Well, I just googled into this page by accident. I see many suggestions regarding this and that software tool, but does any tool actually provide an answer? The actual answer is:

[a,b,c] = [200,375,425]

How did I get this? By writing a quick program in the Maxima programming language to find it via "brute force" searching. It only took about 10 minutes to write, seeing as how I'm familiar with the Maxima language. It took a few seconds for the program to run. Here is the program:

euler_solve():= block
(
[ a, b, A, B, end:1000],

for a thru end do
    (
    for b thru end do
        (
        c: 1000 -a -b,
        if c < 0 then
            b:end
        else if a^2 + b^2 = c^2 then
            (
            A:a,
            B:b,
            a:end,
            b:end
            )
        )
    ),
return( [A,B,c])
);

You can just cut and paste the above code into the wxMaxima user interface, which I run under Ubuntu and not MS Windows. Then you just enter the function name: euler_solve(), hit return, wait a few seconds, and out pops the answer. This particular kind of problem is so simple that you could use any general-purpose programming language to do the search.

妥活 2024-08-16 02:37:59

尝试在 py 中应用 二分法 来查找给定间隔的根:

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..

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..
℡Ms空城旧梦 2024-08-16 02:37:59

再想一想,我详细了解了 sage,显然它是最好的数学免费软件。

只是一些不同的 python 数学相关库,它的集成绝对很棒。

Sage 中包含的数学包:

Algebra GAP, Maxima, Singular 
Algebraic Geometry  Singular
Arbitrary    Precision
Arithmetic  GMP, MPFR, MPFI,    NTL
Arithmetic Geometry PARI, NTL,      
mwrank, ecm Calculus    Maxima, SymPy, 
GiNaC Combinatorics Symmetrica,     
Sage-Combinat Linear Algebra    Linbox,
IML Graph Theory    NetworkX Group     
Theory  GAP Numerical
computation GSL,    SciPy, NumPy,
ATLAS

Sage 中包含的其他包:

Command line    IPython Database    ZODB,
Python Pickles, SQLite Graphical
Interface   Sage Notebook, jsmath
Graphics    Matplotlib, Tachyon3d, GD,
Jmol Interactive 
programming language  Python 
Networking  Twisted

On second thoughts, I went through sage in detail and clearly it is the best math free software available.

Just some of the different python math related libraries, it integrates is absolutely awesome.

Mathematics packages contained in Sage:

Algebra GAP, Maxima, Singular 
Algebraic Geometry  Singular
Arbitrary    Precision
Arithmetic  GMP, MPFR, MPFI,    NTL
Arithmetic Geometry PARI, NTL,      
mwrank, ecm Calculus    Maxima, SymPy, 
GiNaC Combinatorics Symmetrica,     
Sage-Combinat Linear Algebra    Linbox,
IML Graph Theory    NetworkX Group     
Theory  GAP Numerical
computation GSL,    SciPy, NumPy,
ATLAS

Other packages contained in Sage:

Command line    IPython Database    ZODB,
Python Pickles, SQLite Graphical
Interface   Sage Notebook, jsmath
Graphics    Matplotlib, Tachyon3d, GD,
Jmol Interactive 
programming language  Python 
Networking  Twisted
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文