我正在尝试制作一个计算pi的值并将其打印在终端上的程序,但只有一部分显示在屏幕上
package main
import (
"fmt"
)
func gregorypi() float64 {
numerator := 1.0
divisor := 3.0
var result float64
for i := 0; i <= 100000000; i++ {
if i%2 == 0 {
result += numerator / divisor
divisor += 2
} else {
result -= numerator / divisor
divisor += 2
}
}
return (4 * (1 - result))
}
func main() {
fmt.Sprint(gregorypi())
}
输出为:3.1415926435897683
如何制作整个值?
如果它有助于回答这个问题:我使用的公式是Gregory-Leibniz的公式
答案 0 :(得分:7)
func Sprint(a ...interface{}) string
使用默认格式作为其操作数和返回值的Sprint格式 结果字符串。当两个操作数都没有时,在操作数之间添加空格 是一个字符串。
fmt.Sprint
返回一个string
。不要扔掉它;打印出来。
例如,
func main() {
s := fmt.Sprint(gregorypi())
fmt.Println(s)
}
游乐场:https://play.golang.org/p/zOVtJc5HfXT
输出:
3.1415926435897683
如果要获得比IEEE 754 64位浮点数更精确的结果,请使用Go math/big
包。
例如,
package main
import (
"fmt"
"math/big"
)
func gregorypi(iter int, prec uint) *big.Float {
one := big.NewFloat(1)
two := big.NewFloat(2)
four := big.NewFloat(4)
numerator := big.NewFloat(1).SetPrec(prec)
divisor := big.NewFloat(3).SetPrec(prec)
result := new(big.Float).SetPrec(prec)
for i := 0; i <= iter; i++ {
if i%2 == 0 {
result.Add(result, new(big.Float).Quo(numerator, divisor))
} else {
result.Sub(result, new(big.Float).Quo(numerator, divisor))
}
divisor.Add(divisor, two)
}
return new(big.Float).Mul(four, (new(big.Float).Sub(one, result)))
}
func main() {
pi := gregorypi(1000000, 4096)
s := fmt.Sprint(pi)
for i, j := 0, 0; i < len(s); i = j {
j = i + 60
if j > len(s) {
j = len(s)
}
fmt.Println(s[i:j])
}
}
输出:
3.1415916535917932347126498832691903993221476025342620143148
652250543253683419302770934570540444696092784515646197918416
151531004207388567190381995115109764938931650751911723670828
705935671760975424757204401786734958287682330276123443546400
855990841037108771486255447137253791363986086026524209725177
041621398938122502069099548344075841960714856836014332632487
249750055949826053894250927777836988620276187954914335474236
918693730264540456485214156731536507281567237095178205850787
841887779856892311307656085287982909183503886914799719930651
362811646060939082163336282527001630768619465916054216662233
647867947277285894357821722722774052560440050583160360321106
944441543917458948854721791262992799982426130041196627951982
504267630916391384654303083557011574782570253034162966525670
594481466474403221843818413155653700689258246423537757630787
951957260253561222183715232613769610553278998905210089847178
951692922815021787390361813556619177840043555176857090268624
902791212304201317960964869615176784400855500998688041903616
187746299057333789390884081442894661717258714989758581139759
403617872623424695182488545758897457727485849932980050101014
208290473579625783313281627594640164541223264510142763045401
708614153731722941036904397534247