Scala BigDecimal 如何显示更多小数?
首先,我知道有一个关于 1 除以 3 的类似主题。但是,我的代码完全不同,我不知道如何将那里给出的信息应用到我的情况。我将不胜感激任何和所有的帮助。
我在 Scala 中制作了一个 Pi 计算器,并在代码末尾打印了结果。但是,我想要更多的小数位数,但我不知道如何实现这一点。我当前的输出是:
Expected decimals: 34
3.141592653589793238462643383279500
这是代码:
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)
}
}
}
First of all, I am aware that there is a similar topic regarding the division of 1 by 3. However, my code is quite different and I don't know how to apply the information given there to my situation. I would appreciate any and all help.
I made a Pi calculator in Scala and at the end of the code I print the result. However, I want to have a much larger number of decimals and I don't know how to achieve that. My current output is :
Expected decimals: 34
3.141592653589793238462643383279500
Here's the 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)
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建
BigDecimal
实例时,您必须提供不同的java.math.MathContext
。请注意,这会影响计算的精度,而不仅仅是输出中打印的小数位数。这与单纯的数字格式化有很大不同。You have to supply a different
java.math.MathContext
when you create your instances ofBigDecimal
. Note that this effects the precision of the calculation, not only how many decimals are printed on output. This is quite different from the mere formatting of numbers.