Question

Tout d'abord, je suis conscient qu'il ya un sujet similaire en ce qui concerne la division de 1 par 3. Cependant, mon code est tout à fait différent et je ne sais pas comment appliquer les informations données là pour ma situation. Je vous serais reconnaissant toute aide.

J'ai fait une calculatrice Pi en Scala et à la fin du code imprimer le résultat. Cependant, je veux avoir un plus grand nombre de décimales et je ne sais pas comment y parvenir. Ma sortie actuelle est:

Expected decimals: 34
3.141592653589793238462643383279500

Voici le code:

package theBrain
object Calculator 
{
def main(args: Array[String]) 
{

var i = 100
var j = 100
var lastValueOnFirstLine = j+i
var array = new Array [BigDecimal] (0)

var counter = i-1

for (d <- j to lastValueOnFirstLine by 1)
{
  var almostPi = BigDecimal(0)
  var pi = BigDecimal(0)

  for (b <- 0 to d by 1)
  {
      var partialAnswer = (if (b%2 != 0) {-1} else {1} )/((BigDecimal(2)*BigDecimal(b))+BigDecimal(1))
      almostPi = partialAnswer + almostPi

  }
  pi = 4*almostPi
 array = array:+pi
}

for (z <- counter to 0 by -1){
var array2 = new Array [BigDecimal] (0)
var length = array.length -2
for (a <- 0 to length by 1){

var result = (array(a)+array(a+1))/2
array2 = array2:+result
}
array = array2
counter -= 1
}

for (element <- array) {
println("Expected decimals: " + element.precision)
println(element)
}

}
}
Était-ce utile?

La solution

Vous devez fournir un java.math.MathContext différent lorsque vous créez vos instances de BigDecimal. Notez que ces effets la précision du calcul, non seulement le nombre de décimales sont imprimées sur la sortie. Ceci est tout à fait différent de la simple mise en forme des nombres.

scala> BigDecimal(1) / 3
res0: scala.math.BigDecimal = 0.3333333333333333333333333333333333

scala> res0.precision
res1: Int = 34

scala> BigDecimal(1, new java.math.MathContext(50)) / 3
res2: scala.math.BigDecimal = 0.33333333333333333333333333333333333333333333333333

scala> res2.precision
res3: Int = 50
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top