Skip to content

Commit

Permalink
Add a working arbitrary integer solution to pi series
Browse files Browse the repository at this point in the history
  • Loading branch information
samiam2013 committed Oct 1, 2023
1 parent 408e513 commit 16e308e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 1-elementary/elementary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,12 +302,27 @@ func TestAlternatingSeries(t *testing.T) {
}
}

func TestAlternatingSeriesBig(t *testing.T) {
response := AlternatingSeriesBig()
correct := big.NewFloat(math.Pi)
if !withinBig(response, correct, big.NewFloat(.001)) {
t.Errorf("AlternatingSeries() = '%v'; want '%v'", response, correct)
}
}

func within(a, b, tolerance float64) bool {
difference := math.Abs(a - b)
belowTolerance := difference < tolerance
return belowTolerance
}

func withinBig(a, b, tolerance *big.Float) bool {
difference := a.Sub(a, b)
absDiff := new(big.Float).Abs(difference)
belowTolerance := absDiff.Cmp(tolerance) == -1
return belowTolerance
}

// captureOutput takes in a function to catch the output,
//
// optionally taking in lines of input for stdin
Expand Down
39 changes: 39 additions & 0 deletions 1-elementary/exercise11sumSeriesBigInt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package elementary

import (
"math/big"
)

// Write a program that computes the sum of an alternating series
// where each element of the series is an expression of the form
// ((-1)^{k+1})/(2 * k-1)
// for each value of k from 1 to a million, multiplied by 4.

// AlternatingSeries computes the series in exercise 11 and prints the reuslt
func AlternatingSeriesBig() *big.Float {
i := big.NewInt(1)
limit := big.NewInt(1000000)
sum := big.NewFloat(0)
for i.Cmp(limit) == -1 {
k := *i
k.Add(&k, big.NewInt(1))
numerator := big.NewInt(0)
numerator.Exp(big.NewInt(-1), &k, nil)

k.Sub(&k, big.NewInt(1)) // k = k - 1 because 1 was added above and it's reused

denominator := big.NewInt(0)
denominator.Mul(big.NewInt(2), &k)
denominator.Sub(denominator, big.NewInt(1))

value := big.NewFloat(0)
value.SetPrec(100000)
value.SetInt(numerator)
value.Quo(value, big.NewFloat(0).SetInt(denominator))

sum.Add(sum, value)
// fmt.Println("sum, value: ", sum, value)
i.Add(i, big.NewInt(1))
}
return sum.Mul(sum, big.NewFloat(4))
}

0 comments on commit 16e308e

Please # to comment.