首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala失配MonteCarlo

Scala失配MonteCarlo
EN

Stack Overflow用户
提问于 2017-11-19 15:42:08
回答 1查看 53关注 0票数 0

我尝试在Scala中实现Monte算法的一个版本,但是我有一个小问题。在我的第一个循环中,我与Unit和Int不匹配,但我不知道如何解决这个问题。

谢谢你的帮助!

代码语言:javascript
复制
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一起工作的人。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-19 17:09:09

for循环不返回任何内容,所以这就是为什么您的方法返回Unit,但希望List[Int]作为返回类型是List[Int]。第二,您没有正确地使用scala插值。它不会打印错误的值。你忘了在字符串之前使用's‘。第三,如果想返回列表,首先需要一个列表,在这个列表中,您将积累每个迭代的所有值。因此,我假设您试图返回所有迭代的错误。因此,我创建了一个errorList,它将存储所有的错误值。如果您想返回其他内容,可以相应地修改代码。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47378677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档