解算案例
本文为实现python一元方程解算的源码案例(后续不定期更新)
# -*- coding: UTF-8 -*-
from sympy import *
#设置一些可能抛出的异常
def Warn(type):
if type == "missEquater":
print "You missed the euqater!"
elif type == "excessiveEquater":
print "You entered too much equater!"
#检查输入方程是否有超过一个等号
def CheckEquation_1(equation):
equalNums = 0
for char in equation:
if char == "=":
equalNums += 1
return equalNums
#纯化等式,去掉空格
def PurifyEquation(equation):
PureEquation = ""
for char in equation:
if char != " ":
PureEquation += char
return PureEquation
#标准化等式方法
def NormalizationEquation_1(equation):
resultEquation = ""
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
index = 1
for char in equation:
if index < len(equation):
if char in numbers and equation[index] in letters:
resultEquation += char + "*"
else:
resultEquation += char
else:
resultEquation += char
index += 1
return resultEquation
#右式化简方案(传入右式)
def RightSimplify(equation):
#最终输出结果
simplifiedEquation = []
#补上加号
if equationIn[0] != "-" and equationIn[0] != "+":
equation = "+" + equation
#print equation
#获取各个单项式的去符号结果
rightEquationContents = equation.replace("+", " ").replace("-", " ").split(" ")
rightEquationContents.remove("")
#获取各个单项式符号
rightSymbols = []
for char in equation:
if char == "+":
rightSymbols.append("+")
elif char == "-":
rightSymbols.append("-")
#将单项式(去符号)与单项式合并写入返回值列表
currentIndex = 0
for contents in rightEquationContents:
simplifiedEquation.append([rightSymbols[currentIndex], contents])
#递增指针
currentIndex += 1
#返回处理结果
return simplifiedEquation
equationIn = raw_input("Equation here:")
print "Puring equation..."
equationIn = PurifyEquation(equationIn)
print equationIn
print "Normalizing equation..."
equationIn = NormalizationEquation_1(equationIn)
print equationIn
equalNums = CheckEquation_1(equationIn)
if equalNums == 0:
Warn("missEquater")
elif equalNums > 1:
Warn("excessiveEquater")
else:
print "Split the equation..."
#分离等式左右两边
splitedEquation = equationIn.split("=")
#左式准备
leftEquation = splitedEquation[0]
print splitedEquation
print "Split the right side of the equation..."
rightEquation = RightSimplify(splitedEquation[1])
print rightEquation
#循环右边的单项式
for single in rightEquation:
if single[0] == '+':
leftEquation += '-' + single[1]
else:
leftEquation += '+' + single[1]
print "Standard form simplified: " + leftEquation + "=0"
print solve(leftEquation, "x")
之前写的粒子模拟引擎未来会用上新的解算系统