Skip to content

Instantly share code, notes, and snippets.

@tatyusa
Created January 6, 2014 02:52
Show Gist options
  • Save tatyusa/8277492 to your computer and use it in GitHub Desktop.
Save tatyusa/8277492 to your computer and use it in GitHub Desktop.
Newton法で並列に根探査するプログラム
package main
import (
"fmt"
"time"
"math/cmplx"
"math/rand"
)
// 試行回数
const trail = 1000
// 計算精度
const precise = 0.001
// 探査範囲
const x_min = -1
const x_max = 1
const y_min = -1
const y_max = 1
// 根探査する関数
func f(z complex128) complex128 {
return 1 + z + cmplx.Pow(z,2)
}
// 根探査する関数の導関数
func fp(z complex128) complex128 {
return 1 + 2 * z
}
func main(){
rand.Seed(time.Now().UTC().UnixNano())
result := make([]complex128, 0, trail) // 要改良
c := make(chan complex128, trail)
for i:=0;i<trail;i++ {
go func(z complex128, c chan complex128){
var d complex128
for i:=0;i<100;i++ { // 要改良
d = f(z) / fp(z)
if cmplx.Abs(d)<precise { break }
z = z - d
}
c <- z
}(complex(random(x_min,x_max),random(y_min,y_max)), c)
}
var z complex128
for i:=0;i<trail;i++ {
z = <- c
if(!isIn(z,result)){
fmt.Println(z)
result = append(result, z)
}
}
fmt.Println(len(result),"roots")
}
func random(min,max float64) float64{
return min + (max - min) * rand.Float64()
}
func isIn(z complex128, result []complex128) bool{
for i:=0;i<len(result);i++ {
if cmplx.Abs(z - result[i]) < precise*10 { return true }
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment