blog_projekty/obliczanie_pi/golang/main.go
2024-11-04 10:30:41 +01:00

102 lines
2.3 KiB
Go

package main
import (
"fmt"
"math/big"
"net/http"
"strconv"
"time"
)
func calculatePi(n int) *big.Float {
precision := uint(n * 14)
pi := new(big.Float).SetPrec(precision)
pi.SetInt64(0)
one := new(big.Float).SetInt64(1)
two := new(big.Float).SetInt64(2)
four := new(big.Float).SetInt64(4)
five := new(big.Float).SetInt64(5)
six := new(big.Float).SetInt64(6)
eight := new(big.Float).SetInt64(8)
sixteen := new(big.Float).SetInt64(16)
for i := 0; i < n; i++ {
k := new(big.Float).SetInt64(int64(i))
// Obliczanie 16^i
powSixteen := new(big.Float).SetInt64(1)
for j := 0; j < i; j++ {
powSixteen.Mul(powSixteen, sixteen)
}
// Obliczanie 1/16^i
denominator := new(big.Float).SetPrec(precision)
if powSixteen.Sign() != 0 {
denominator.Quo(one, powSixteen)
} else {
continue
}
// Obliczanie poszczególnych składników
term1 := new(big.Float).SetPrec(precision)
term1.Mul(eight, k)
term1.Add(term1, one)
term1.Quo(four, term1)
term2 := new(big.Float).SetPrec(precision)
term2.Mul(eight, k)
term2.Add(term2, four)
term2.Quo(two, term2)
term3 := new(big.Float).SetPrec(precision)
term3.Mul(eight, k)
term3.Add(term3, five)
term3.Quo(one, term3)
term4 := new(big.Float).SetPrec(precision)
term4.Mul(eight, k)
term4.Add(term4, six)
term4.Quo(one, term4)
// Łączenie składników
sum := new(big.Float).SetPrec(precision)
sum.Sub(term1, term2)
sum.Sub(sum, term3)
sum.Sub(sum, term4)
// Mnożenie przez 1/16^i i dodawanie do wyniku
sum.Mul(sum, denominator)
pi.Add(pi, sum)
}
return pi
}
func main() {
http.HandleFunc("/pi", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
precisionStr := r.URL.Query().Get("precision")
precision, err := strconv.Atoi(precisionStr)
if err != nil {
http.Error(w, "Invalid precision parameter", http.StatusBadRequest)
return
}
start := time.Now()
pi := calculatePi(precision)
duration := time.Since(start)
// Format PI to specified precision
piFormatted := fmt.Sprintf("%.*f", precision, pi)
response := fmt.Sprintf(`{"pi": "%s", "time": "%v", "language": "Go"}`, piFormatted, duration)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, response)
})
fmt.Println("Go server starting on port 8081...")
http.ListenAndServe(":8081", nil)
}