Option Explicit Public a() As Double Public b() As DoublePublic Function Guass(n As Integer) As Boolean '列主元高斯消去法Dim k As Integer '未知数的个数 Dim i As Integer Dim j As Integer Dim StoreNum As Double '存数据 Dim StoreIndex As Integer '保存下标 Dim MultiNum As Double '保存乘子 For k = 1 To n - 1 StoreNum = a(k, k) StoreIndex = k For i = k + 1 To n '找列主元 If a(i, k) > StoreNum Then StoreNum = a(i, k) StoreIndex = i End If Next i If StoreNum = 0 Then Guass = False Exit Function '系数为0,退出 End If If StoreNum > a(k, k) Then '交换系数 For i = k To n StoreNum = a(k, i) a(k, i) = a(StoreIndex, i) a(StoreIndex, i) = StoreNum Next i StoreNum = b(k) '交换常数项 b(k) = b(StoreIndex) b(StoreIndex) = StoreNum End If '以上几步是找列主元,是为了减少对误差 For i = k + 1 To n '消元 MultiNum = a(i, k) / a(k, k) '计算乘子 For j = k To n a(i, j) = a(i, j) - MultiNum * a(k, j) Next j b(i) = b(i) - MultiNum * b(k) Next i Next k '到此原函数的系数矩阵已经是上三角了 '下面要做的是回代,解保存在b()中 For i = n To 1 Step -1 StoreNum = 0 For j = i + 1 To n StoreNum = StoreNum + a(i, j) * b(j) Next j b(i) = (b(i) - StoreNum) / a(i, i) Next i End Function例如要算 3*x1+4*x2=6 2*x1+6*x2=8 redim a( 1 to 2) redim b (1 to 2) 输入系数矩阵 a(1,1)=3 a(1,2)=4 a(2,1)=2 a(2,2)=6 输入常数项 b(1)=6 b(2)=8 if guass then print "X1=" & b(1),"X2=" & b(2) else print "系数矩阵奇异“ end if 这个函数可以解n此线性方程组。 我一直想写,但又怕麻烦, 你想要我就写了。可以把找列主元的部分删除, 程序不会有影响,但误差会增大。 有问题E_mail:[email protected]
Public a() As Double
Public b() As DoublePublic Function Guass(n As Integer) As Boolean
'列主元高斯消去法Dim k As Integer '未知数的个数
Dim i As Integer
Dim j As Integer
Dim StoreNum As Double '存数据
Dim StoreIndex As Integer '保存下标
Dim MultiNum As Double '保存乘子 For k = 1 To n - 1
StoreNum = a(k, k)
StoreIndex = k
For i = k + 1 To n '找列主元
If a(i, k) > StoreNum Then
StoreNum = a(i, k)
StoreIndex = i
End If
Next i
If StoreNum = 0 Then
Guass = False
Exit Function '系数为0,退出
End If
If StoreNum > a(k, k) Then '交换系数
For i = k To n
StoreNum = a(k, i)
a(k, i) = a(StoreIndex, i)
a(StoreIndex, i) = StoreNum
Next i
StoreNum = b(k) '交换常数项
b(k) = b(StoreIndex)
b(StoreIndex) = StoreNum
End If
'以上几步是找列主元,是为了减少对误差
For i = k + 1 To n '消元
MultiNum = a(i, k) / a(k, k) '计算乘子
For j = k To n
a(i, j) = a(i, j) - MultiNum * a(k, j)
Next j
b(i) = b(i) - MultiNum * b(k)
Next i
Next k
'到此原函数的系数矩阵已经是上三角了
'下面要做的是回代,解保存在b()中
For i = n To 1 Step -1
StoreNum = 0
For j = i + 1 To n
StoreNum = StoreNum + a(i, j) * b(j)
Next j
b(i) = (b(i) - StoreNum) / a(i, i)
Next i
End Function例如要算
3*x1+4*x2=6
2*x1+6*x2=8
redim a( 1 to 2)
redim b (1 to 2)
输入系数矩阵
a(1,1)=3
a(1,2)=4
a(2,1)=2
a(2,2)=6
输入常数项
b(1)=6
b(2)=8
if guass then
print "X1=" & b(1),"X2=" & b(2)
else
print "系数矩阵奇异“
end if
这个函数可以解n此线性方程组。
我一直想写,但又怕麻烦,
你想要我就写了。可以把找列主元的部分删除,
程序不会有影响,但误差会增大。
有问题E_mail:[email protected]