我尝试在Scala中实现Monte算法的一个版本,但是我有一个小问题。在我的第一个循环中,我与Unit和Int不匹配,但我不知道如何解决这个问题。
谢谢你的帮助!
import scala.math._
import scala.util.Random
import scala.collection.mutable.ListBuffer
object Main extends App{
def MonteCarlo(list: ListBuffer[Int]): List[Int] = {
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
print("Approximative value of pi : $p \tError: $error")
}
}
var liste = ListBuffer (200, 2000, 4000)
MonteCarlo(liste)
}一个通常和Python一起工作的人。
发布于 2017-11-19 17:09:09
for循环不返回任何内容,所以这就是为什么您的方法返回Unit,但希望List[Int]作为返回类型是List[Int]。第二,您没有正确地使用scala插值。它不会打印错误的值。你忘了在字符串之前使用's‘。第三,如果想返回列表,首先需要一个列表,在这个列表中,您将积累每个迭代的所有值。因此,我假设您试图返回所有迭代的错误。因此,我创建了一个errorList,它将存储所有的错误值。如果您想返回其他内容,可以相应地修改代码。
def MonteCarlo(list: ListBuffer[Int]) = {
val errorList = new ListBuffer[Double]()
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
errorList += error
println(s"Approximative value of pi : $p \tError: $error")
}
errorList
}
scala> MonteCarlo(liste)
Approximative value of pi : 3.26 Error: 0.11840734641020667
Approximative value of pi : 3.12 Error: 0.02159265358979301
Approximative value of pi : 3.142 Error: 4.073464102067881E-4
res9: scala.collection.mutable.ListBuffer[Double] = ListBuffer(0.11840734641020667, 0.02159265358979301, 4.073464102067881E-4)https://stackoverflow.com/questions/47378677
复制相似问题