Scala 斯卡拉错配蒙特卡洛
我试图在Scala中实现Monte Carlo算法的一个版本,但我有一个小问题。 在我的第一个循环中,Unit和Int不匹配,但我不知道如何解决这个问题 谢谢你的帮助Scala 斯卡拉错配蒙特卡洛,scala,for-loop,mismatch,Scala,For Loop,Mismatch,我试图在Scala中实现Monte Carlo算法的一个版本,但我有一个小问题。 在我的第一个循环中,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] =
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)
}
导入scala.math_
导入scala.util.Random
导入scala.collection.mutable.ListBuffer
对象主应用程序{
def MonteCarlo(列表:ListBuffer[Int]):列表[Int]={
for(ifor
循环不返回任何内容,因此您的方法返回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)
def MonteCarlo(列表:ListBuffer[Int])={
val errorList=新的ListBuffer[Double]()
为了