用golang写一个单纯性算法
时间: 2023-05-19 20:07:25 浏览: 255
单纯性算法举例
好的,以下是用 Golang 编写单纯性算法的示例代码:
```
package main
import "fmt"
func main() {
points := [][]float64{{0, 0}, {1, 0}, {0, 1}, {1, 1}, {0.5, 0.5}}
simplex := Simplex(points)
fmt.Println(simplex)
}
func Simplex(points [][]float64) [][]float64 {
n := len(points[0])
simplex := make([][]float64, n+1)
for i := range simplex {
simplex[i] = make([]float64, n)
}
for i := range simplex[0] {
simplex[0][i] = -points[len(points)-1][i]
}
for i, p := range points {
for j := range p {
simplex[i+1][j] = p[j]
}
}
for {
c := findNegative(simplex[0])
if c < 0 {
break
}
r := findRatio(simplex, c)
if r < 0 {
return nil
}
pivot(simplex, r, c)
}
return simplex
}
func findNegative(row []float64) int {
for i, v := range row {
if v < 0 {
return i
}
}
return -1
}
func findRatio(simplex [][]float64, c int) int {
n := len(simplex)
r := -1
for i := 1; i < n; i++ {
if simplex[i][c] <= 0 {
continue
}
if r == -1 {
r = i
continue
}
if simplex[i][n-1]/simplex[i][c] < simplex[r][n-1]/simplex[r][c] {
r = i
}
}
return r
}
func pivot(simplex [][]float64, r, c int) {
n := len(simplex)
pivot := simplex[r][c]
for i := range simplex[r] {
simplex[r][i] /= pivot
}
for i := range simplex {
if i == r {
continue
}
factor := simplex[i][c]
for j := range simplex[i] {
simplex[i][j] -= factor * simplex[r][j]
}
}
}
```
这个算法实现了单纯性算法,可以用来求解线性规划问题。在这个示例代码中,我们使用了一个包含 5 个点的简单例子来测试算法的正确性。
阅读全文