原理可以参考
https://zh.wikipedia.org/wiki/%E9%AB%98%E6%96%AF%E6%B6%88%E5%8E%BB%E6%B3%95
这里给出使用分数表示计算过程的高斯消元法写法
github地址:https://github.com/YIWANFENG/Algorithm-github
#!/usr/bin/env python3.5
# -*-coding: utf-8 -*-
"""
Created on 2018-6-9
@author: YWF
高斯消元法求解线性方程,
数字采用分数精确表示,无近似
"""
import numpy as np
def gcd(a,b):
if a < b:
c = a
a = b
b = c
while a % b != 0:
c = a % b
a = b
b = c
return b
def lcm(a,b):
return a * b / gcd(a,b)
class Fractional:
def __init__(self,num,den):
self.numerator = num
if(den == 0):
print("Error den")
self.denominator = den
pass
def Simplify(self):
if self.numerator == 0:
return Fractional(0,1)
gcd_ = gcd(self.denominator,self.numerator)
if gcd_ != 1:
self.denominator /= gcd_
self.numerator /= gcd_
return self
def __sub__(self, other):
lcm_ = lcm(self.denominator,other.denominator)
self.numerator *= lcm_ / self.denominator
num = self.numerator - other.numerator * lcm_ / other.denominator
return Fractional(num,lcm_).Simplify()
def __add__(self, other):
lcm_ =