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

Lak*_*sad 21 python math equation numpy scipy

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

使用类似Mathematica的网络wolframalpha.com来解决它们很简单.但这并不能提供iPython shell的舒适性和便利性.

是否有一个简单的库来处理来自python shell的线性和二次方程?

就个人而言,我发现使用卡西欧991 MS科学计算器非常方便.我知道如何设置变量,求解方程式,并做很多事情.我希望这样的工具最好在ipython shell中使用.我很惊讶没有找到任何.圣人并没有给我留下足够的印象; 也许我错过了什么.

Aut*_*tic 46

sympy正是你要找的.


Pau*_*lan 22

你最好的答案是不可接受的.

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

答案是"SAGE就是这么做的."

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

http://maxima.sourceforge.net/


Wil*_*ein 10

以下是使用Python(通过Sage)解决原始问题的方法.这基本上澄清了Paul McMillan所说的话.

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]]
Run Code Online (Sandbox Code Playgroud)


csl*_*csl 7

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

如果方程需要整数解,那么你应该为Python搜索Diophantine方程求解器.

请注意,使用Project Euler的简单求解器忽略了这一点.有趣和教育的部分是学习如何使用原始方法自己解决它!


And*_*ler 5

你看过SciPy吗?

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

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


Joh*_*ren 5

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

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

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

下面是一个优化问题的例子 (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
Run Code Online (Sandbox Code Playgroud)

优化问题通过以下 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
Run Code Online (Sandbox Code Playgroud)