解算案例
本文為實現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")
之前寫的粒子模擬引擎未來會用上新的解算系統